使用OAuth访问Gmail的Atom源

6

我正在尝试使用OAuth从Python应用程序中获取Gmail原子源。我有一个可以下载Google Reader源的工作应用程序,我认为只需要更改范围和源URL就可以了。替换URL后,我仍然可以成功获取请求和访问令牌,但是当我尝试使用访问令牌获取源时,我会收到“401未经授权”错误。这是我的简单测试程序:

import urlparse
import oauth2 as oauth

scope = "https://mail.google.com/mail/feed/atom/"
sub_url = scope + "unread"

request_token_url = "https://www.google.com/accounts/OAuthGetRequestToken?scope=%s&xoauth_displayname=%s" % (scope, "Test Application")
authorize_url = 'https://www.google.com/accounts/OAuthAuthorizeToken'
access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken'

oauth_key = "anonymous"
oauth_secret = "anonymous"

consumer = oauth.Consumer(oauth_key, oauth_secret)
client = oauth.Client(consumer)

# Get a request token.
resp, content = client.request(request_token_url, "GET")
request_token = dict(urlparse.parse_qsl(content))

print "Request Token:"
print "    - oauth_token        = %s" % request_token['oauth_token']
print "    - oauth_token_secret = %s" % request_token['oauth_token_secret']
print

# Step 2: Link to web page where the user can approve the request token.
print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
print

raw_input('Press enter after authorizing.')

# Step 3: Get access token using approved request token
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
client = oauth.Client(consumer, token)

resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))

print "Access Token:"
print "    - oauth_token        = %s" % access_token['oauth_token']
print "    - oauth_token_secret = %s" % access_token['oauth_token_secret']
print

# Access content using access token
token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
client = oauth.Client(consumer, token)

resp, content = client.request(sub_url, 'GET')
print content

您会注意到我在使用“anonymous / anonymous”作为我的OAuth密钥/秘密,如Google未注册应用程序的文档中所述。这对于Google Reader很好用,所以我不认为它不能适用于Gmail。有人知道为什么会出现问题,或者我该如何进行故障排除吗?谢谢。


你自己实现的原因是什么?可以查看http://libgmail.sourceforge.net/。无论如何,这不是你问题的答案,所以我在评论中提供了它! - alecwh
1
@alecwh:libgmail似乎要求我的程序知道用户的用户名和密码。如果可能的话,我想避免这种情况,这就是为什么我想使用oauth的原因。 - Will
1个回答

3
您可能想尝试使用OAuth访问Google的IMAP服务器,而不是使用ATOM feed。在一些搜索后,我找到了这个
“Gmail支持通过他们称之为XOAUTH的标准进行IMAP和SMTP的OAuth验证。这使您可以使用OAuth令牌和密钥对Gmail的IMAP和SMTP服务器进行身份验证。它还具有额外的好处,允许您使用原始的SMTP和IMAP库。python-oauth2包提供了实现XOAUTH并包装imaplib.IMAP4_SSL和smtplib.SMTP的IMAP和SMTP库。这使您可以使用标准的Python库使用OAuth凭据连接到Gmail。”
来自http://github.com/simplegeo/python-oauth2

谢谢。这看起来就是我需要的。我不确定为什么 Gmail 订阅源不起作用,但据我所知,在 gdata API 中它似乎是二等公民。 - Will

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