Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Python command-line application that makes requests to the Gmail API.
Prerequisites
To run this quickstart, you'll need:
- Python 2.6 or greater.
- The pip package management tool.
- Access to the internet and a web browser.
- A Google account with Gmail enabled.
Step 1: Enable the Gmail API
- Use this wizard to create or select a project in the Google Developers Console and automatically enable the API.
- In the sidebar on the left, select APIs & auth and then Consent screen. Select an EMAIL ADDRESS, enter a PRODUCT NAME if not already set, and click the Save button.
- In the sidebar under APIs & auth select Credentials. In the new tab that opens, click Create new Client ID.
- Select the application type Installed application, the installed application type Other, and click the Create Client ID button.
- Click the Download JSON button under your new client ID. Move this file
to your working directory and rename it
client_secret.json.
Step 2: Install the Google Client Library
Run the following command to install the library using pip:
$ pip install --upgrade google-api-python-client
See the library's installation page for the alternative installation options.
Step 3: Set up the sample
Create a file named quickstart.py in your working directory and copy in the
following code:
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
def main():
"""Shows basic usage of the Gmail API.
Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print 'No labels found.'
else:
print 'Labels:'
for label in labels:
print label['name']
if __name__ == '__main__':
main()
Step 4: Run the sample
Run the sample using the following command:
$ python quickstart.py
The sample will attempt to open a new window or tab in your default browser. If this fails, copy the URL from the console and manually open it in your browser.
If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
- Click the Accept button.
- The sample will proceed automatically, and you may close the window/tab.
Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.