Home > database >  Google script for gmail api watch: No way to get message id for fresh emails?
Google script for gmail api watch: No way to get message id for fresh emails?

Time:03-19

been using google script to trigger action when new mail comes in.

This is my doPost function

function doPost(e) {
  var contents = JSON.parse(e.postData.contents);
  var message = contents.message;
  var data = JSON.parse(Utilities.newBlob(Utilities.base64Decode(message.data)).getDataAsString());

  var historyId = data.historyId;

}

With this, I have access to historyId,... but to get the message object, or at least the message id of the mail, I will be needing to show the history. so:

 Gmail.Users.History.list("me", {"startHistoryId": historyId});

The expected result of the code above would be:

{ historyId: '######', history: [ { messages: [Object], id: '#####' } ] }

This is is true for mails that have threads or histories already.

BUT, this isn't the case for new mails. It only shows the historyId { historyId: '######' }

My question is, is there really no way to get the message object for new mails? If not, how?

CodePudding user response:

Gmail.Users.Message.list() returns:

An email message.

JSON representation

{ "id": string, "threadId": string, "labelIds": [ string ], "snippet": string, "historyId": string, "internalDate": string, "payload": { object (MessagePart) }, "sizeEstimate": integer, "raw": string }

CodePudding user response:

The reason why the history.list method is just returning the ID is explained in its documentation

Returns history records after the specified startHistoryId. The supplied startHistoryId should be obtained from the historyId of a message, thread, or previous list response. History IDs increase chronologically but are not contiguous with random gaps in between valid IDs. (...) If you receive no nextPageToken in the response, there are no updates to retrieve and you can store the returned historyId for a future request.

This means that you will only get the messages after the specified History ID, so if you're tracking changes to the User's most recent History ID you will get blank responses.

To get the message objects you can use messages.list instead. And based on the quote above it seems that there's no easy way to get a list of all History IDs so they expect you to store the current ID when a change occurs and when you detect another change you can use the stored ID instead of the new one to get the most recent messages.

  • Related