2011-03-04 65 views
8

我想使用Oauth在Python中連接到Gmail。現在我已經從Google獲得了xoauth.py腳本(link),並且生成一個令牌工作正常,但是如何才能在另一個腳本中使用該令牌?這將在Django。使用imaplib和oauth與Gmail連接

現在我的腳本日誌中這樣的:

m = imaplib.IMAP4_SSL("imap.gmail.com") 
m.login("[email protected]", "password") 

但我想要的東西更安全。

回答

11

下面是一個使用oauth2 module使用OAuth,自述採取認證的例子:

import oauth2 as oauth 
import oauth2.clients.imap as imaplib 

# Set up your Consumer and Token as per usual. Just like any other 
# three-legged OAuth request. 
consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret') 
token = oauth.Token('your_users_3_legged_token', 
    'your_users_3_legged_token_secret') 

# Setup the URL according to Google's XOAUTH implementation. Be sure 
# to replace the email here with the appropriate email address that 
# you wish to access. 
url = "https://mail.google.com/mail/b/[email protected]/imap/" 

conn = imaplib.IMAP4_SSL('imap.googlemail.com') 
conn.debug = 4 

# This is the only thing in the API for impaplib.IMAP4_SSL that has 
# changed. You now authenticate with the URL, consumer, and token. 
conn.authenticate(url, consumer, token) 

# Once authenticated everything from the impalib.IMAP4_SSL class will 
# work as per usual without any modification to your code. 
conn.select('INBOX') 
print conn.list() 

相當多的清潔比使用xoauth

+0

嗨Acorn,我是oauth2和imaplib的新手,我現在有一些問題,你可以回答他們:http://stackoverflow.com/questions/17976626/oauth2-and-imap-connection-with-gmail – Cacheing 2013-07-31 18:01:20

+1

我不明白「your_users_3_legged_token」和「your_users_3_legged_token_secret」 「來自:/ – daveoncode 2016-10-24 12:18:40

3

以下是使用Google的xoauth.py中的例程連接到IMAP的示例。它會輸出一些調試信息,因此您可能需要切換到使用oauth軟件包進行實際應用。至少,這應該讓你開始:

import imaplib 
import random 
import time 

import xoauth 

MY_EMAIL = '[email protected]' 
MY_TOKEN = # your token 
MY_SECRET = # your secret 

def connect(): 
    nonce = str(random.randrange(2**64 - 1)) 
    timestamp = str(int(time.time())) 

    consumer = xoauth.OAuthEntity('anonymous', 'anonymous') 
    access = xoauth.OAuthEntity(MY_TOKEN, MY_SECRET) 
    token = xoauth.GenerateXOauthString(
     consumer, access, MY_EMAIL, 'imap', MY_EMAIL, nonce, timestamp) 

    imap_conn = imaplib.IMAP4_SSL('imap.googlemail.com') 
    imap_conn.authenticate('XOAUTH', lambda x: token) 
    imap_conn.select('INBOX') 

    return imap_conn 

connect() 
+0

這工作確實,多虧了代碼示例。我如何使用oauth包來做到這一點? – HankSmackHood 2011-03-04 17:02:05

+0

如果您可以容忍打印語句,或者只是將它們從本地副本中撕掉,則可以繼續使用xoauth。我沒有親自使用oauth,但我想象的api是相似的。在oauth存儲庫中有一個例子:[oauth client example](http://oauth.googlecode.com/svn/code/python/oauth/example/client.py) – samplebias 2011-03-04 18:12:42

3

谷歌有一個很好的示例代碼來做OAuth2 and IMAP。另外請確保您的範圍是 正確。

'scope': 'https://mail.google.com/' 
'access_type': 'offline' 

下面是在谷歌例如

import base64 
import imaplib 

my_email = "[email protected]" 
access_token = "" #Oauth2 access token 

auth_string = GenerateOAuth2String(my_email, access_token, base64_encode=False) 
TestImapAuthentication(my_email, auth_string) 


def TestImapAuthentication(user, auth_string): 
    """Authenticates to IMAP with the given auth_string. 

    Prints a debug trace of the attempted IMAP connection. 

    Args: 
    user: The Gmail username (full email address) 
    auth_string: A valid OAuth2 string, as returned by GenerateOAuth2String. 
     Must not be base64-encoded, since imaplib does its own base64-encoding. 
    """ 
    print 
    imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') 
    imap_conn.debug = 4 
    imap_conn.authenticate('XOAUTH2', lambda x: auth_string) 
    imap_conn.select('INBOX') 


def GenerateOAuth2String(username, access_token, base64_encode=True): 
    """Generates an IMAP OAuth2 authentication string. 

    See https://developers.google.com/google-apps/gmail/oauth2_overview 

    Args: 
    username: the username (email address) of the account to authenticate 
    access_token: An OAuth2 access token. 
    base64_encode: Whether to base64-encode the output. 

    Returns: 
    The SASL argument for the OAuth2 mechanism. 
    """ 
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) 
    if base64_encode: 
    auth_string = base64.b64encode(auth_string) 
    return auth_string 
+0

Google提供了OAuth 1&2示例。他們的OAuth 1 API被貶值,我無法使用django-social-auth工作。以上是OAuth 2與django-social-auth正常工作。 – 2013-08-31 19:11:56