python - 如何使用python访问gmail?

标签 python oauth gmail

我想使用 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')

但是demo有一些bug,不知道怎么调试。console的信息:

  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

我需要帮助。

最佳答案

auth_string 不应该是 base64encoded。我相信 IMAP4.authenticate 会为您编码它。无论如何它对我有用。

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

关于python - 如何使用python访问gmail?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21776590/

相关文章:

oauth - 实现一个 2 Legged OAuth Provider

python - 为什么每次我播放 "play"音乐时 python 都会发出奇怪的声音?

python - 如果一个类有 __len__ 和 __getitem__ 但没有 __iter__,为什么 mypy 不认为它是可迭代的

java - 我可以在本地运行并调试使用 Google API 的 Web 应用程序吗? [GWT+GAE]

c# - 从 C# 读取 gmail 帐户的 Atom 提要

google-api - 有关 : Gmail Sidebar Gadget Deprecation 的问题

php - 在 Zend Mail 中以 mbox 格式从 Gmail 中获取电子邮件

python - 在Python中调用citeparser函数

python - 使用不同的功能获得不同的对象大小

oauth-2.0 - 通过 XOAUTH2 的 Office 365 SMTP 身份验证