Search code examples
pythonemailgoogle-apigmailgmail-api

How to check for incoming new messages using Gmail API


I have set up a python script that can pull data from Gmail account, but I would like to set it up in a way that it would only pull new message since the last time I made the API call (I will be pinging the server regularly).

I have looked at Push notification and Pub/Sub, but I am not quite sure if these are relevant or I should be looking at something else. Gmail also has Users.history: list function, but I am wondering if this can be used in any useful way.


Solution

  • You could list messages as you usually do, but saying that you want messages after a certain timestamp. This way, you can poll for new messages e.g. every minute, giving the last time you checked for messages in seconds since the epoch:

    Request

    q = is:unread AND after:<time_since_epoch_in_seconds>
    
    GET https://www.googleapis.com/gmail/v1/users/me/messages?q=is%3Aunread+AND+after%3A1446461721&access_token={YOUR_API_KEY}
    

    Response

    {
     "messages": [
      {
       "id": "150c7d689ef7cdf7",
       "threadId": "150c7d689ef7cdf7"
      }
     ],
     "resultSizeEstimate": 1
    }
    

    Then you just save the timestamp when you issued the request, and use this timestamp one minute later.