how to print the body of gmail in python using gmail api?

Question:

Hello everyone I’m attempting to use the Gmail API to print out specific emails from a sender. I’ve managed to do some research and watched some videos on how to get the sender and the subject printed off but for some reason, I cant get the body of the message to print off. I’ve looked through the Gmail API and haven’t found anything to help with printing the body in text form.

Any help with printing off the body of the email, please…

service = build('gmail', 'v1', credentials=creds)
results = service.users().messages().list(userId='me', labelIds=['INBOX'], q="from:specific email, is:unread").execute()

messages = results.get('messages', [])

if not messages:
  print("You have no New Messages.")

else:
   message_count = 0
   for message in messages: 
       msg = service.users().messages().get(userId='me', id=message['id']).execute()
       message_count= message_count + 1
       email_data= msg['payload']['headers']
       for values in email_data:
           name = values["name"]
           if name == "From":
               from_name = values ["value"]
               print(from_name)
               subject= [j['value'] for j in email_data if j["name"]=="Subject"]
               print(subject)

This code like I said pulls the specific email and prints the sender, and the subject all I’m missing is the body.

I’ve tried following what was posted in this stackoverflow:
How to retrieve the whole message body using Gmail API (python)
But I couldn’t manage to get it to work

Asked By: OrbitDuster

||

Answers:

In your script, how about the following modification?

Modified script:

service = build("gmail", "v1", credentials=creds)
results = service.users().messages().list(userId="me", labelIds=["INBOX"], q="from:specific email, is:unread").execute()

messages = results.get("messages", [])

if not messages:
    print("You have no New Messages.")

else:
    message_count = 0
    for message in messages:
        msg = service.users().messages().get(userId="me", id=message["id"]).execute()
        message_count = message_count + 1
        email_data = msg["payload"]["headers"]
        for values in email_data:
            name = values["name"]
            if name == "From":
                from_name = values["value"]
                print(from_name)
                subject = [j["value"] for j in email_data if j["name"] == "Subject"]
                print(subject)

        # I added the below script.
        for p in msg["payload"]["parts"]:
            if p["mimeType"] in ["text/plain", "text/html"]:
                data = base64.urlsafe_b64decode(p["body"]["data"]).decode("utf-8")
                print(data)
  • In this case, please add import base64.

  • When this script is run, both the text body and the HTML body are retrieved. For example, when you want to retrieve only the text body, please modify if p["mimeType"] in ["text/plain", "text/html"]: to if p["mimeType"] == "text/plain":.

Reference:

Answered By: Tanaike
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.