Skip to content

Instantly share code, notes, and snippets.

@jeffskinnerbox
Created December 23, 2015 01:40
Show Gist options
  • Save jeffskinnerbox/bb802a02e97db907a1d4 to your computer and use it in GitHub Desktop.
Save jeffskinnerbox/bb802a02e97db907a1d4 to your computer and use it in GitHub Desktop.
Test tool to print labels (aka mailboxes) for a Gmail account using Google Gmail APIs
#!/usr/bin/env python
"""Test tool to print labels (aka mailboxes) for a Gmail account using Google Gmail APIs # NOQA
When this tool starts, it reads a local file, called CLIENT_SECRET_FILE,
containing the Cline ID / Client Secret any existing credentials.
If the credentials don't exits, it then prompts you, via the web browser,
to authenticate to get them. It the credentials exist, but need to be renewed,
it will do that.
Credentials are place within the directory DIR_HOME/CREDENTIAL_DIR and
the credentials file is called CREDENTIAL_FILE. It contains
the Client ID, Client Secret, Access Token, Refresh Token, etc.
Based on: https://developers.google.com/gmail/api/quickstart/python
"""
# for support of both Python 2 and Python 3
from __future__ import print_function
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.compose', ]
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
CREDENTIALS_FILE = 'gmail-python-quickstart.json'
CREDENTIALS_DIR = '.credentials'
DIR_HOME = '~'
import httplib2 # comprehensive HTTP client library
import os # miscellaneous operating system interfaces
# library for accessing resources protected by OAuth 2.0
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse # command-line parsing module
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
def get_credentials():
"""Gets valid user credentials from storage or request new ones.
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.
"""
# location where credentials are stored
home_dir = os.path.expanduser(DIR_HOME)
credential_dir = os.path.join(home_dir, CREDENTIALS_DIR)
# if credential store doesn't exist, create it
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, CREDENTIALS_FILE)
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
# if the credentials don't exist/invalid, get new credentials and store them
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 compatibility with Python 2.6
credentials = tools.run(flow, store)
print('\nStoring credentials to ' + credential_path)
return credentials
def main():
"""Shows basic OArth functionality of the Gmail API
Creates a Gmail API service object and outputs a list of label
(aka mailebox) names of the user's Gmail account.
"""
from apiclient import discovery
# get the credentials
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', [])
# print out the labels (aka mailboxes)
if not labels:
print('\nNo labels found.')
else:
print('\nLabels:')
for label in labels:
print(label['name'])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment