Search code examples
pythonpython-3.xgmailgmail-api

Search for email using message-id using Gmail API in Python


I am trying to get a particular email by searching for its message-id using the following API: https://developers.google.com/gmail/api/guides/filtering

e.g message_id = "<C6P4M-GEE8PzO8qf0=oTQ3ZJeFB_uASDAAF9AJSRRiNuUVBzan0w@mail.gmail.com>"

Could I implement it by modifying the following:

MESSAGE = GMAIL.users().messages().list(userId='me',labelIds='INBOX').execute()

But how do I modify it to search only for the particular email with the message_id?

Currently I have tried using an extremely inefficient solution which works by scanning the entire inbox using messages.list and then find the matching email message-id.


Solution

  • Found the solution:

    var = "Rfc822msgid:" + message_id
    MESSAGE = GMAIL.users().messages().list(userId='me',q=var).execute() 
    

    References: https://support.google.com/mail/answer/7190?hl=en