Recently I was doing some experiments with python and gmail.Python has a handy imap library(imaplib.And there is a good tutorial which helped me to get started.There is one small problem with this approch, you have to store you password in plain text!
Gmail supports another authentication method called OAuth2, which don’t need actual password being stored.I coudln’t find any good tutorial on accessing gmail in python and oauth2 using imaplib ,so decided to write on my own.
Accessing gmail python way:
First step is to register your application,details on how to do this and brief explanation of OAuth2 is available from google. After registration, you will be having two paramters “client id” and “client secret“.
Now download oauth2.py from here,it has many useful functions for handling OAuth protocol.
Firstly you need to get refresh token for the user, refresh token allows an application to get emails on behalf of the user without needing the actual password.Refrsh tokens will be by google and given to the app when a user authenticate and authorise an app.
To get refresh token for a user,he/she must approve the application,this can be achieved by asking user to visit a google link generated based on the client id.Once user approves the app,an authorization code will be generated which can be used to to generate refresh token.Following code will generate the URL, and once user enters the authorization code,it generates refresh and access tokens.Use chrome to open the link,firefox didn’t work for me!!.
import oauth2 client_id="your cliend id" client_secret="your client secret" print 'To authorize token, visit this url and follow the directions:' print ' %s' % oauth2.GeneratePermissionUrl(client_id') authorization_code = raw_input('Enter verification code: ') response = oauth2.AuthorizeTokens(client_id,client_secret,authorization_code) print "Refresh Toke :",response['refresh_token'] print "Access Token :",response['access_token'] print "Expires in :",response['expires_in']
Access tokens are temperory tokens generated based upon the refresh token and client id.To access email,one need to supply access token to the IMAP API.Normaly they have an expiry time of 1 hour, so every one hour its needs to be renewed.Refresh tokens never expires as long as user don’t revoke it via security tab in his/her google account.
Following code will renew access token.
import oauth2 client_id ="your cliend id" client_secret ="your client secret" refresh_token ="refresh token for the user" response = oauth2.RefreshToken(lient_id,client_secret,refresh_token) print New Access Token :",response['access_token'] print "Expires in :",response['expires_in']
Once a valid access token is available,access mail is as simple as telling IMaplib the token value.
import oauth2 import imaplib import email emailid = "email id of the user" client_id ="your cliend id" client_secret ="your client secret" refresh_token ="refresh token for the user" oauth2String = oauth2.GenerateOAuth2String(emailid,access_token,base64_encode=False) #before passing into IMAPLib access token needs to be converted into string mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.authenticate('XOAUTH2', lambda x: oAuthString) mail.select("inbox") # connect to inbox. #rest of the code to play with emails #for more info please check the link on top
Few more examples about accessing gmail using python and imaplib:
1. Send email alert when a particular job is completed in EC2