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 "tech163@fusionswift.com" OR FROM "tech163@fusionswift.com"')

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.

有帮助吗?

解决方案

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 "tech163@fusionswift.com") (FROM "tech163@fusionswift.com"))'

其他提示

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_='from@ya.ru', text='"the text"'), NOT(OR(A(answered=False), A(new=True))), to='to@ya.ru')

Of course you can use all library tools

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top