【问题标题】:use imaplib and oauth for connection with Gmail使用 imaplib 和 oauth 连接 Gmail
【发布时间】:2011-07-08 19:11:54
【问题描述】:

我想使用 Oauth 在 Python 中连接到 Gmail。现在我已经从 Google (link) 获得了 xoauth.py 脚本,并且生成令牌工作正常,但是我如何在另一个脚本中使用它呢?它将在 Django 中。

现在我的脚本是这样登录的:

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("example@gmail.com", "password")

但我想要更安全的东西。

【问题讨论】:

    标签: python django oauth imaplib


    【解决方案1】:

    这是一个使用 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/your_users_email@gmail.com/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 干净得多。

    【讨论】:

    • 嗨 Acorn,我是 oauth2 和 imaplib 的新手,我现在有一些问题,你能回答他们吗:stackoverflow.com/questions/17976626/…
    • 我不知道“your_users_3_legged_token”和“your_users_3_legged_token_secret”的来源:/
    【解决方案2】:

    Google 有一个很好的示例代码可以做OAuth2 and IMAP。还要确保您的范围是 正确。

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

    以下是谷歌示例中的代码示例

    import base64
    import imaplib
    
    my_email = "xyz@gmail.com"
    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
    

    【讨论】:

    • Google 提供 OAuth 1 和 2 示例。他们的 OAuth 1 API 已被贬值,我无法让它与 django-social-auth 一起使用。上面的 OAuth 2 与 django-social-auth 配合得很好。
    【解决方案3】:

    这是一个使用 Google 的xoauth.py 中的例程连接到 IMAP 的示例。它会输出一些调试信息,因此您可能希望将oauth 包用于实际应用程序。至少这应该让你开始:

    import imaplib
    import random
    import time
    
    import xoauth
    
    MY_EMAIL = 'xxx@gmail.com'
    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()
    

    【讨论】:

    • 这确实有效,谢谢。我将如何使用 oauth 包?
    • 如果您可以容忍打印语句,您可以继续使用 xoauth,或者直接从本地副本中删除它们。我没有亲自使用过 oauth,但我想 api 是相似的。 oauth 仓库中有一个例子:oauth client example
    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 2014-10-14
    • 2011-07-06
    • 1970-01-01
    • 2012-05-10
    • 2019-12-24
    • 2013-09-30
    • 2017-05-14
    相关资源
    最近更新 更多