Created
September 25, 2013 13:25
-
-
Save ib-lundgren/6699537 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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'] |
Thanks a lot, was looking for something like this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you tell me how to use this flask? Thanks...