GMail API - 获取线程的最后一条消息

Vin*_*ent 9 python gmail-api

我在Python/Google App Engine上使用GMail API.我有一个返回某些线程ID的查询,现在我想得到每个线程的最后一条消息.由于结果不一定按日期排序,我想知道什么是最有效的API调用呢?

根据以下评论,我设置了以下批处理功能:

if threads != []:
    count = 0 #start a new batch request after every 1000 requests
    batch = BatchHttpRequest(callback=get_items)
    for t in threads:
        batch.add(service.users().threads().get(userId=email, id=t), request_id=some_id)
        count += 1
        if count % 1000: #batch requests can handle max 1000 entries
            batch.execute(http=http)
            batch = BatchHttpRequest(callback=get_items) 
    if not count % 1000:
            batch.execute(http=http)
Run Code Online (Sandbox Code Playgroud)

然后执行get_items,其中包括跟随逻辑运行以查明线程中的最后一封电子邮件是否是已发送的项目.

def get_items(request_id, response, exception):
  if exception is not None:
      print 'An error occurred: %s' % exception
  else:
      for m in response['messages']: #check each of the messages in the response
          if m['historyId'] == response['historyId']: #if it equals the historyId of the thread
              if 'SENT' in m['labelIds']: #and it is marked as a sent item
                  item = m #use this message for processing
Run Code Online (Sandbox Code Playgroud)

这似乎适用于大多数情况,但是,有些情况下,上面创建的"item"包含2个具有不同historyIds的消息.不确定是什么导致了这一点,我想知道之前只是为它创建一个解决方法...

Tho*_*lle 3

Gmail API 现在支持该字段internalDate

InternalDate - 内部消息创建时间戳(纪元毫秒),它确定收件箱中的排序。

获取线程中的最新消息并不比 User.thread 难: get-request,询问各个消息的 id 和内部日期,并找出最后创建的消息。

fields = messages(id,internalDate)

GET https://www.googleapis.com/gmail/v1/users/me/threads/14e92e929dcc2df2?fields=messages(id%2CinternalDate)&access_token={YOUR_API_KEY}
Run Code Online (Sandbox Code Playgroud)

回复:

{
 "messages": [
  {
   "id": "14e92e929dcc2df2",
   "internalDate": "1436983830000" 
  },
  {
   "id": "14e92e94a2645355",
   "internalDate": "1436983839000"
  },
  {
   "id": "14e92e95cfa0651d",
   "internalDate": "1436983844000"
  },
  {
   "id": "14e92e9934505214",
   "internalDate": "1436983857000" // <-- This is it!
  }
 ]
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,谢谢!将很快尝试并确认它是否有效。 (2认同)