The easiest way to use imaplib with Gmail is to use the X-GM-RAW
attribute as described in the Gmail Imap Extensions page.
The process would be like this:
First connect to the account with the appropriate email and password:
c = imaplib.IMAP4_SSL('imap.gmail.com', 993)
email = 'eggs@spam'
password = 'spamspamspam'
c.login(email, password)
Then connect to one of the folders/labels:
c.select("INBOX")
If necessary, you can list all the available folders/labels with c.list()
.
Finally, use the search method:
gmail_search = "has:attachment eggs OR spam"
status, data = c.search(None, 'X-GM-RAW', gmail_search)
In the gmail_search
you can use the same search syntax used in gmail advanced search.
The search command will return the status of the command and the ids of all the messages that match your gmail_search.
After this you can fetch each messages by id with:
for id in data[0].split():
status, data = gmail.fetch(id, '(BODY[TEXT])')