pythonpython-3.xgmail-api

python 3.x - Gmail api get title and sender


I have just started working with the Gmail API and have followed the Oauth2.0 tutorial to get the autherisation code. my code so far is:

from oauth2client import client
import webbrowser
import httplib2

flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/gmail.readonly',
    redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()
webbrowser.open_new(auth_uri)

authcode = input("Enter auth code: ")

credentials = flow.step2_exchange(authcode)
http_auth = credentials.authorize(httplib2.Http())

I would like to test the API by making a request which gets the subject and sender of the latest unread message in this kind of format:

#pseudocode
get latestMessage
if latestMessage.read == True:
    print("you have no unread messages)
else:
    print("you have a new email: " + latestMessage.subject + " from" + latestmessage.sender)

Solution

  • As stated here, if you want headers like To, From, Subject then you can call messages.get(format=METADATA) or however it looks in the language you're using. You may check the example in the documentation.

    Returns:
        An object containing a base64url encoded email object.
      """
    
      message = MIMEText(message_text)
      message['to'] = to
      message['from'] = sender
      message['subject'] = subject
      return {'raw': base64.urlsafe_b64encode(message.as_string())}
    

    You may also check the answer in this SO question on how to get the sender of the email.