Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python IMAP Search from or to designated email address

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.

like image 441
Tech163 Avatar asked May 12 '12 11:05

Tech163


2 Answers

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]"))'
like image 93
Santiago Alessandri Avatar answered Nov 06 '22 14:11

Santiago Alessandri


Try to use IMAP query builder from https://github.com/ikvk/imap_tools

from imap_tools import A, AND, OR, NOT
# AND
A(text='hello', new=True)  # '(TEXT "hello" NEW)'
# OR
OR(text='hello', date=datetime.date(2000, 3, 15))  # '(OR TEXT "hello" ON 15-Mar-2000)'
# NOT
NOT(text='hello', new=True)  # 'NOT (TEXT "hello" NEW)'
# complex
A(OR(from_='[email protected]', text='"the text"'), NOT(OR(A(answered=False), A(new=True))), to='[email protected]')

Of course you can use all library tools

like image 1
Vladimir Avatar answered Nov 06 '22 14:11

Vladimir