1
votes

I'm trying to get mail body by gmail api.

message = self.service.users().messages().get(userId=user, id=i,format='full').execute()

When I put my last email Id. Always I can't find contents in content['payload']['body']['data']

It's shows like this.

"body": {
    "size": 0
}

Of course it has message body.

I can get sumally by content['snippet'] ,but I can't get the message body body.

If you have any idea about this, please help me.

1
Could you provide the logs? - abielita
Although I'm not sure whether this is what you want, how about res = [e['body']['size'] for e in message['payload']['parts']] or res = [e['body']['data'] for e in message['payload']['parts']]? message is from your snippet. - Tanaike
The part you are looking for is located in different locations depending on what type of message it is. This answer might give some inspiration. - Tholle

1 Answers

6
votes

I solved my problem by this method. Thank you Tanaike!

def data_encoder(text):
    if len(text)>0:
        message = base64.urlsafe_b64decode(text)
        message = str(message, 'utf-8')
        message = email.message_from_string(message)
    return message


def readMessage(content)->str:
    message = None
    if "data" in content['payload']['body']:
        message = content['payload']['body']['data']
        message = data_encoder(message)
    elif "data" in content['payload']['parts'][0]['body']:
        message = content['payload']['parts'][0]['body']['data']
        message = data_encoder(message)
    else:
        print("body has no data.")
    return message