title: GMail API - Get last message of a thread
body: <p>I'm using the GMail API on Python / Google App Engine. I have a query which returns certain thread ids, and now I would like to get the last message of each thread. Since results are not necessarily sorted by date, I'm wondering what would be the most efficient API call for this?</p>
  
  <p>Based on comments below I've set up the following batch function:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>This then executes get_items, which amongst other things runs following logic to find out if the last email in a thread was a sent item.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>This seems to work for most cases, however, there are cases where "item" as created above contains 2 messages with different historyIds. Not sure what is causing this and I would like to know before just creating a work-around for it...</p>