-
-
Save andytriboletti/400840 to your computer and use it in GitHub Desktop.
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
import oauth2 as oauth | |
import imaplib | |
consumer = oauth.Consumer("your_consumer_key", "your_consumer_secret") | |
token = oauth.Token("the_users_oauth_key_from_3_legged_auth", | |
"the_users_oauth_key_from_3_legged_auth") | |
class GmailClient(imaplib.IMAP4_SSL): | |
BASE_URL = "https://mail.google.com/mail/b/%s/imap/" | |
HOST = 'imap.googlemail.com' | |
def __init__(self, account, consumer, token, parameters=None): | |
imaplib.IMAP4_SSL.__init__(self, self.HOST) | |
self.account = account | |
self.consumer = consumer | |
self.token = token | |
self.parameters = parameters | |
def authenticate(self): | |
self.debug = 4 | |
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', | |
lambda x: self._get_xoauth_string()) | |
self.select('INBOX') | |
def _get_xoauth_string(self): | |
request = oauth.Request.from_consumer_and_token(self.consumer, | |
self.token, "GET", self._get_url(), self.parameters) | |
signing_method = oauth.SignatureMethod_HMAC_SHA1() | |
request.sign_request(signing_method, self.consumer, | |
self.token) | |
params = [] | |
for k,v in sorted(request.iteritems()): | |
if v is not None: | |
params.append('%s="%s"' % (k, oauth.escape(v))) | |
return "%s %s %s" % ("GET", self._get_url(), ','.join(params)) | |
def _get_url(self): | |
return self.BASE_URL % self.account | |
if __name__ == "__main__": | |
client = GmailClient("[email protected]", consumer, token) | |
client.authenticate() | |
client.select('INBOX') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment