1

I am trying to read the access code from gmailAPI, coded is not fetching the full/complete message body.I am using Python code for it

I tried using various formats to fetch the complete message like Raw and Full

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import dateutil.parser as parser
from bs4 import BeautifulSoup
import base64

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
       if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)



     results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()
     messages = results.get('messages', [])
          if not messages:
         print("No messages found.")
     else:
         print("Message snippets:")
         for message in messages:
             msg = service.users().messages().get(userId='me', id=message['id']).execute()
             print(msg['snippet'])

if __name__ == '__main__':
    main()

Expected Result:You requested a one-time access code to log into your member account. Please enter the following access code within the next 10 minutes, and click Submit: Your One-Time Access Code: 8627816 This is an automated email. Please do not reply to this message. If you have any questions, please contact Optum GovID IT Help Desk. Thank you, Optum GovID

Actual: Access Code Notification You requested a one-time access code to log into your member account. Please enter the following access code within the next 10 minutes, and click Submit: Your One-Time Access

Note:Original message(Expected) has many spaces and e.t.c

Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54

1 Answers1

1

Answer:

You are retrieving a snippet of the message rather than the full message body.

Explanation & Fix:

As per the Users.messages Resource Documentation of the Gmail API, the snippet is "A short part of the message text.". In order to get the full message, you need to get the raw message and decode it as it is returned in base64.

In your for loop, you need to replace:

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    print(msg['snippet'])

with:

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    body = base64.b64decode(msg['raw'])
    print(body)

References:

Community
  • 1
  • 1
Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54
  • @ommse2etestGovid Glad to help! For documentation purposes if you can, please accept the answer that's been helpful to you - it helps other people that have the same issue in the future find the solution too :) – Rafa Guillermo Oct 22 '19 at 06:28