Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading