How to detect if label was added to email via gmail api?

喜夏-厌秋 提交于 2019-12-11 12:33:17

问题


I try to detect if email message got one particular label. Following the documentation here I do deserialize push message and got historyId eg. 390100 but it turns out I can't get exact 390100 history entry.

history.list api has startHistoryId param and docs states that you get all history after that historyId.

However what is even worse 390100 history event is empty (sic!). The real entry with labelsAdded was before that historyId in push notification eg. at 39086 which is not published

Tried to workaround and subtract eg. 15 form 390100 and do history.list with startHistoryId 39085

If I'm in luck and 39085 still exists I will not get 404 and eventually got information that my label was added to message. But that seems like a bad hack for me.

Is there any reliable way to know at which point in history label was added, and is there reliable way to search history backwards ?

I also cross posted rant/issue here


回答1:


The historyId you get in the push notification simply represents the current time. So if you use this historyId when asking for history, you will not get any results. Use this workflow instead:

  1. Save a historyId.
  2. When you get a push, use the historyId you saved in step 1, and you will get all the relevant changes.
  3. Save the hisotryId you got in the push notification, and use it next time.
  4. Repeat step 2.

Example

  1. I get a starting historyId with the getProfile-operation:

Request

GET https://www.googleapis.com/gmail/v1/users/me/profile?fields=historyId&access_token={YOUR_API_KEY}

Response

{
 "historyId": "655156"
}
  1. I get the push, and list the history since last time:

Request

GET https://www.googleapis.com/gmail/v1/users/me/history?labelId=STARRED&startHistoryId=655156&fields=history%2FlabelsAdded&key={YOUR_API_KEY}

Response:

{
 "history": [
  {
   "labelsAdded": [
    {
     "message": {
      "id": "151237ed0d001368",
      "threadId": "151237ed0d001368",
      "labelIds": [
       "STARRED",
       "CATEGORY_UPDATES",
       "INBOX"
      ]
     },
     "labelIds": [
      "STARRED"
     ]
    }
   ]
  }
 ]
}
  1. Save the historyId I got in the push, and use that next time.


来源:https://stackoverflow.com/questions/33846001/how-to-detect-if-label-was-added-to-email-via-gmail-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!