Search code examples
pythonsearchgmailimaplib

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.


Solution

  • 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)')