hyperwiser hyperwiser - 2 months ago 45
Python Question

Python imaplib can't search by from address

I'm trying to find mails matching a particular FROM address. I've looked at this answer but it doesn't work for me.

Here's the relevant code:

import imaplib

conn = imaplib.IMAP4_SSL(IMAPserver)
conn.login(IMAPuserName, IMAPpassword)
retVal, data = conn.select("INBOX")
if retVal != "OK":

All this works. Here are some variations of the search command that don't work:

retVal, data = conn.search(None, 'UNSEEN HEADER FROM "foo@example.com"')

retVal, data = conn.search(None, 'UNSEEN FROM "foo@example.com"')

retVal, data = conn.search(None, 'FROM "foo@example.com"')

retVal, data = conn.search(None, 'HEADER FROM "foo@example.com"')

All of these result in errors like these:

imaplib.error: SEARCH command error: BAD ['Error in IMAP command SEARCH:
Unexpected string as search key: FROM "foo@example.com"']

I've referred to the relevant section of the IMAP v4 RFC but I can't figure out what exactly I'm doing wrong. Any help would be greatly appreciated.


I managed to get info from the guys managing the IMAP server. This was a server problem and not something to do with the code.

The IMAP server in question is a customised version of Dovecot. It actually indexes all mailboxes to make searching etc. faster. In this particular case the index for my mailbox had gotten corrupted. Re-indexing fixed the problem.