kalidurge
kalidurge

Reputation: 289

Search Gmail using imaplib using double quotes - how to avoid search command error

I need to search someone's Gmail account for a specific phrase, "foo bar". If I search foo bar without double quotes I get >125,000 emails, when I search with double quotes (from the browser), I get the 180 relevant emails I'm looking for. However, imaplib's search method won't let me use double quotes. Is there anything I can do about this?

This is what I've already tried:

import imaplib
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(USERNAME,PASSWORD)
mail.select(mail_box)
Type, data = mail.search(None, ('Since 01-Jan-2016'), ('BODY "foo bar"'))

^^ works but returns >125,000 emails, mostly irrelevant - anything with both foo and bar

Type, data = mail.search(None, ('Since 01-Jan-2016'), ('BODY ""foo bar""'))
Type, data = mail.search(None, ('Since 01-Jan-2016'), ('BODY "\"foo bar\""'))
Type, data = mail.search(None, ('Since 01-Jan-2016'), ('BODY """foo bar"""'))

^^^ all of the above throw the following error: "error: SEARCH command error: BAD [b'Could not parse command']"

Any ideas would be much appreciated.

Upvotes: 1

Views: 352

Answers (2)

kalidurge
kalidurge

Reputation: 289

As suggested by Max above, this is what worked:

import imaplib
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(USERNAME,PASSWORD)
mail.select(mail_box)

Type, data = mail.uid('search', None, ('Since 01-Jan-2016'), 'X-GM-RAW', r'"\"foo bar\""')

Note if you're using mail.uid() search, you need to update your fetch call as well to...

mail.uid('fetch', ID, '(RFC822)')

Upvotes: 2

Max
Max

Reputation: 10985

This should work:

mail.search(None, r'BODY "\"Security Alert\""')

r to turn it into a raw string so the backslashes won't be interpreted by Python. Then the backslash gets sent to the server and interpreted properly.

You should be able to adapt this format for your use.

Note: to see what's being sent, temporary set your mail.debug to a high number, like 4. This shows the traffic. Seeing this I saw the quote was not actually being escaped (because Python was treating the backspace as an escape for it).

mail.debug = 4

Upvotes: 0

Related Questions