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?
Based on comments below I've set up the following batch function:
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)
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.
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
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...
The Gmail API now supports the field internalDate
.
internalDate - The internal message creation timestamp (epoch ms), which determines ordering in the inbox.
Getting the latest message in a thread is no harder than a User.thread: get-request, asking for the id and internalDate of the individual messages, and figuring out which was created last.
fields = messages(id,internalDate)
GET https://www.googleapis.com/gmail/v1/users/me/threads/14e92e929dcc2df2?fields=messages(id%2CinternalDate)&access_token={YOUR_API_KEY}
Response:
{
"messages": [
{
"id": "14e92e929dcc2df2",
"internalDate": "1436983830000"
},
{
"id": "14e92e94a2645355",
"internalDate": "1436983839000"
},
{
"id": "14e92e95cfa0651d",
"internalDate": "1436983844000"
},
{
"id": "14e92e9934505214",
"internalDate": "1436983857000" // <-- This is it!
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With