1

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Nori
  • 2,340
  • 1
  • 18
  • 41
  • Could you provide the logs? – abielita Jun 15 '18 at 15:27
  • 1
    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 Jun 16 '18 at 08:37
  • The part you are looking for is located in different locations depending on what type of message it is. [This answer](https://stackoverflow.com/questions/37445865/gmail-api-where-to-find-body-of-email-depending-of-mimetype/37463491#37463491) might give some inspiration. – Tholle Jun 17 '18 at 11:20

1 Answers1

6

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
Rashmi Singh
  • 519
  • 1
  • 8
  • 20
Nori
  • 2,340
  • 1
  • 18
  • 41
  • @Nori - My apologies for mistakenly downvoting your answer when I actually meant to upvote it. So I edited it by removing the commented line. I will upvote the same once it gets peer reviewed. – Rashmi Singh Oct 17 '19 at 11:56