如何使用Python访问Gmail?

3

我想使用Python和OAuth2.0访问Gmail,所以我从"http://google-mail-oauth2-tools.googlecode.com/svn/trunk/python/oauth2.py"下载了oauth2.py。下面是我的演示代码:

import oauth2
import imaplib
import email
from oauth2client.client import OAuth2WebServerFlow
from launchpadlib.credentials import access_token_page

email = 'karlvorndoenitz@gmail.com'
client_id = 'client_id'
client_secret = 'client_secret'
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://mail.google.com/'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
authorization_code = raw_input("Please input the code:").strip()
response = oauth2.AuthorizeTokens(client_id, client_secret, authorization_code)
access_token = response['access_token']
auth_string = oauth2.GenerateOAuth2String(email,access_token,base64_encode=True)
print auth_string
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
imap_conn.select('INBOX')

但是这个演示有一些错误,我不知道如何调试它。控制台上的信息:

  16:58.52 > KOMN1 AUTHENTICATE XOAUTH2
  16:58.79 < + 
  16:58.79 write literal size 204
  16:59.27 < + eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
  16:59.27 write literal size 204
  16:59.27 < KOMN1 NO Invalid SASL argument. d10if1169757igr.56
  16:59.27 NO response: Invalid SASL argument. d10if1169757igr.56
Traceback (most recent call last):
  File "/home/karl/workspace/Gmail/download_gmail/download_gmail_api.py", line 33, in <module>
    imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
  File "/usr/lib/python2.7/imaplib.py", line 351, in authenticate
    raise self.error(dat[-1])
imaplib.error: Invalid SASL argument. d10if1169757igr.56

我需要帮助。


这个页面可能会有用,它与Google邮件OAuth2工具相关。 - loopbackbee
https://developers.google.com/api-client-library/python/guide/aaa_oauth 我会将此页面添加到@goncalopp链接的页面中。这是一个日历,但它有很多解释,可能会帮助您理解。 - Linda Lawton - DaImTo
我认为您不需要OAuth来访问使用IMAP的电子邮件。 - User
1个回答

1

auth_string 不应该被 base64 编码。我相信 IMAP4.authenticate 会为您编码。这种方式对我有效。

例如:auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接