Brent Allard
Brent Allard

Reputation: 396

Gmail API: Python Email Dict appears to be Missing Keys

I'm experiencing a strange issue that seems to be inconsistent with google's gmail API:

If you look here, you can see that gmail's representation of an email has keys "snippet" and "id", among others. Here's some code that I use to generate the complete list of all my emails:

response = service.users().messages().list(userId='me').execute()
messageList = []
messageList.extend(response['messages'])
while 'nextPageToken' in response:
    pagetoken = response['nextPageToken']
    response = service.users().messages().list(userId='me', pageToken=pagetoken).execute()
    messageList.extend(response['messages'])
for message in messageList:
    if 'snippet' in message:
        print(message['snippet'])
    else:
        print("FALSE")

The code works!... Except for the fact that I get output "FALSE" for every single one of the emails. 'snippet' doesn't exist! However, if I run the same code with "id" instead of snippet, I get a whole bunch of ids!

I decided to just print out the 'message' objects/dicts themselves, and each one only had an "id" and a "threadId", even though the API claims there should be more in the object... What gives?

Thanks for your help!

Upvotes: 0

Views: 201

Answers (1)

Brent Allard
Brent Allard

Reputation: 396

As @jedwards said in his comment, just because a message 'can' contain all of the fields specified in documentation, doesn't mean it will. 'list' provides the bare minimum amount of information for each message, because it provides a lot of messages and wants to be as lazy as possible. For individual messages that I want to know more about, I'd then use 'messages.get' with the id that I got from 'list'.

Running get for each email in your inbox seems very expensive, but to my knowledge there's no way to run a batch 'get' command.

Upvotes: 1

Related Questions