如何使用 Gmail 检查收到的新邮件 API

How to check for incoming new messages using Gmail API

我已经设置了一个可以从 Gmail 帐户中提取数据的 python 脚本,但我想将其设置为仅在我上次创建 API 呼叫(我会定期 ping 服务器)。

我查看了推送通知和 Pub/Sub,但我不太确定这些是否相关,或者我应该查看其他内容。 Gmail 也有 Users.history: list 功能,但我想知道是否可以以任何有用的方式使用它。

您可以 list messages 像往常一样,但要在特定时间戳后发送消息。这样,您可以轮询新消息,例如每分钟,给出您上次在 seconds since the epoch:

中检查消息的时间

请求

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}

回应

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

那你就保存发出请求时的时间戳,一分钟后使用这个时间戳。