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

GMail API - Get last message of a thread

我在 Python / Google App Engine 上使用 GMail API。我有一个查询 returns 某些线程 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)

然后执行 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

这似乎适用于大多数情况,但是,在某些情况下,上面创建的 "item" 包含 2 条具有不同 historyId 的消息。不确定是什么原因造成的,我想在为它创建解决方法之前知道...

Gmail API 现在支持字段 internalDate.

internalDate - The internal message creation timestamp (epoch ms), which determines ordering in the inbox.

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

fields = messages(id,internalDate)

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

响应:

{
 "messages": [
  {
   "id": "14e92e929dcc2df2",
   "internalDate": "1436983830000" 
  },
  {
   "id": "14e92e94a2645355",
   "internalDate": "1436983839000"
  },
  {
   "id": "14e92e95cfa0651d",
   "internalDate": "1436983844000"
  },
  {
   "id": "14e92e9934505214",
   "internalDate": "1436983857000" // <-- This is it!
  }
 ]
}