Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to fetch emails from GMail using an OAuth 2 Bearer token and GMails SASL XOAuth2 mechanism.
"""Fetching the latest GMail email using OAuth 2 and IMAP.
Requires requests-oauthlib, which is available on pypi.
Includes a basic SASL XOAUTH2 authentication method for imaplib.
# Credentials you get from registering a new web application in Google API Console
client_id = ''
client_secret = 'your secret'
redirect_uri = 'your callback uri'
# OAuth endpoints given in the Google API documentation
authorization_base_url = ""
token_url = ""
scope = [
from requests_oauthlib import OAuth2Session
google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
# Redirect user to Google for authorization
authorization_url, state = google.authorization_url(authorization_base_url,
# offline for refresh token
# force to always make user click authorize
access_type="offline", approval_prompt="force")
print 'Please go here and authorize,', authorization_url
# Get the authorization verifier code from the callback url
redirect_response = raw_input('Paste the full redirect URL here:')
# Fetch the access token
token = google.fetch_token(token_url, client_secret=client_secret,
print token
r = google.get('')
email = r.json()['email']
print email
def xoauth_authenticate(email, token):
access_token = token['access_token']
def _auth(*args, **kwargs):
return 'user=%s\1auth=Bearer %s\1\1' % (email, access_token)
return 'XOAUTH2', _auth
import imaplib
mail = imaplib.IMAP4_SSL('')
mail.authenticate(*xoauth_authenticate(email, token))'inbox')
latest_id =, 'ALL')[1][0].split()[-1]
raw = mail.fetch(latest_id, "(RFC822)")[1][0][1]
import email
message = email.message_from_string(raw)
print message['date'], message['subject'], message['from']

This comment has been minimized.

Copy link

@arshpreetsingh arshpreetsingh commented Jul 25, 2015

Can you tell me how to use this flask? Thanks...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.