Skip to content

Instantly share code, notes, and snippets.

@Ilgrim
Forked from ib-lundgren/gmail.py
Created July 19, 2020 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ilgrim/760fb299e6f8bb281cc5ec8026d5baae to your computer and use it in GitHub Desktop.
Save Ilgrim/760fb299e6f8bb281cc5ec8026d5baae to your computer and use it in GitHub Desktop.
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 = 'your-id.apps.googleusercontent.com'
client_secret = 'your secret'
redirect_uri = 'your callback uri'
# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/auth"
token_url = "https://accounts.google.com/o/oauth2/token"
scope = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://mail.google.com/",
]
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,
authorization_response=redirect_response)
print token
r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
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('imap.gmail.com')
mail.authenticate(*xoauth_authenticate(email, token))
mail.select('inbox')
latest_id = mail.search(None, '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']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment