Python IMAP Search from or to designated email address

Tech163 picture Tech163 · May 12, 2012 · Viewed 13.6k times · Source

I am using this with Gmail's SMTP server, and I would like to search via IMAP for emails either sent to or received from an address.

This is what I have:

mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login('user', 'pass')
mail.list()
mail.select("[Gmail]/All Mail")

status, email_ids = mail.search(None, 'TO "[email protected]" OR FROM "[email protected]"')

The last line of the error is: imaplib.error: SEARCH command error: BAD ['Could not parse command']

Not sure how I'm supposed to do that kind of OR statement within python's imaplib. If someone can quickly explain what's wrong or point me in the right direction, it'd be greatly appreciated.

Answer

Santiago Alessandri picture Santiago Alessandri · May 12, 2012

The error you are receiving is generated from the server because it can't parse the search query correctly. In order to generate a valid query follow the RFC 3501, in page 49 it is explained in detail the structure.

For example your search string to be correct should be:

'(OR (TO "[email protected]") (FROM "[email protected]"))'