In this tutorial, you’ll learn how to read email from Gmail API using Python, we’ll be making use of the Gmail API.
Go to Google developer console and click on NEW PROJECT to create a new project.
Create Google APIs Project
Once the project has been created, click on add ADD APIS AND SERVICES to add Gmail API.
Add APIs To Google API Project
Once the Gmail has been added to the project, you can enable the API by clicking on ENABLE.
Enable Gmail API
From the project dashboard, click on Create credentials to create credentials for the project.
Create Oauth Client ID
Once you have created the OAuth client credentials, you can download the credentials from the project dashboard.
Download Oauth Client Credentials
Once you have the project credentials handy, let’s start by creating a project folder called readEmailPython. Copy the credential’s json file inside the project folder readEmailPython. Create a file called readEmail.py which will be our program file.
Straight from the Google GMAIL APIs documentation, copy and paste the following code to readEmail.py file:
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
As seen in the above code, the program searches for a token.json file. If the token.json file is not found, then it makes a service call based on the project credentials.json file that you copied into the project folder. A service object is created based on the credentials which can queried to make API calls to GMAIL.
Save the above changes and try to run the python program. The python program launches the Google chrome browser which asks for permission to access the Gmail account. Once the consent is granted a token.json file is created inside the project folder.
Add the following code to query the Gmail INBOX label.
# Call the Gmail API to fetch INBOX
results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()
messages = results.get('messages', [])
The messages array will have all the message id of the emails. You need to query the service object to get detailed information about each message id. Add the following code to get a brief coresponding to each email.
for message in messages:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
print msg['snippet']
Here is how the complete readEmail.py file looks :
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
# Call the Gmail API to fetch INBOX
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()
Save the above changes and execute the Python program and you will the Email snipperts printed on the terminal from the GMAIL API.
You can query the service object to read user profile from Gmail API. service.users().getProfile() method returns the user profile. Add the following code to read the user profile info :
# Query the service object to get User Profile
userInfo = service.users().getProfile(userId='me').execute()
print "UserInfo is \n %s" % (userInfo)
Save the above changes and run the Python program. You will have the user profile info printed in the terminal.
UserInfo is
{u'threadsTotal': 607, u'emailAddress': u'jay3dec@gmail.com', u'historyId': u'346940', u'messagesTotal': 699}
In this tutorial, you learnt how to read email from Gmail API Using Python. In the process of reading email from Gmail API you learnt how to create a Google APIs project and how to create Oauth client credentials.
Thank you for reading!
#python #api