Search code examples
amazon-web-servicesgoogle-cloud-platformaws-lambdagmail-api

Getting Gmail email content from push Pubsub topic subscription in a Lambda function


I'm building an app in which whenever a user receives a new email, it triggers a Lambda function which parses the email's body.

I am having some issues understanding how to make sure I access the right email from within my Lambda function, as the Pubsub event which triggers the Lambda function only contains a "historyId", and not the actual email Id.

I am able to query a list of added messages that arrived since the specified historyId using the history.list API, and each has their own "historyId". as these IDs does not match the one received in the pubsub topic event, I am not sure how to choose the right one.

I Though about taking the one with the highest HistoryId in the history.list call, but it seems like there would be a lot of edge cases (like multiple emails received during the time the lambda function is triggered, etc.)

How can I validate I'm getting the right email in this case?

Thanks in advance.


Solution

  • This is the solution I found:

    • Limit the "watch" method to notify for changes only for labels that I care about. i.e "INBOX", "URGENT".
    • Using the HistoryId i get from the pubsub event, i'm fetching a list of history changes that contains an added message (using history.list(id=historyId) API)
    • filter out history changes with added messages from labels I don't care about, and take the FIRST change that answers my criteria (the closest to the historyId I got from the pubsub event).

    This will guarantee I am parsing the right message.