hyperwiser
hyperwiser

Reputation: 497

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":
        <PRINT SOME ERROR MESSAGE>
        sys.exit(1)

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

retVal, data = conn.search(None, 'UNSEEN HEADER FROM "[email protected]"')

retVal, data = conn.search(None, 'UNSEEN FROM "[email protected]"')

retVal, data = conn.search(None, 'FROM "[email protected]"')

retVal, data = conn.search(None, 'HEADER FROM "[email protected]"')

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 "[email protected]"']

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.

Upvotes: 0

Views: 3688

Answers (2)

hyperwiser
hyperwiser

Reputation: 497

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.

Upvotes: 2

dhke
dhke

Reputation: 15388

As shown in the examples in the docmentation, IMAP.search() expects the search arguments as individual, positional arguments, not as a single string:

conn.search(None, 'UNSEEN', 'HEADER', 'FROM', '[email protected]')
conn.search(None, 'UNSEEN', 'FROM', '[email protected]')
conn.search(None, 'FROM', '[email protected]')
conn.search(None, 'HEADER', 'FROM', '[email protected]')

If you pass in a single argument, imaplib will pass it as a single quoted argument to the SEARCH command.

Again, however, you cannot rely on this, since the quoting only happens for Python 2.x imaplib. Python 3.x imaplib does not do the quoting for you and that particular bug is still open.

One way around that --as stated by the documentation-- is to "pre-quote" the arguments as a list:

conn.search(None, '(UNSEEN HEADER FROM [email protected])')
conn.search(None, '(UNSEEN FROM [email protected])')
conn.search(None, '(FROM [email protected])')
conn.search(None, '(HEADER FROM [email protected])')

But as noted by @Max, this is not supported by some IMAP servers.

Upvotes: 2

Related Questions