在使用服务帐户的Google SMTP服务上使用XOAUTH2时出现“错误请求”(400)

时间:2013-02-28 10:24:49

标签: python smtp google-oauth

我想使用Google的SMTP服务从我的Google帐户发送电子邮件。

所以我转到Google API控制台并创建了一个服务帐户,即...@developer.gserviceaccount.com,并下载了私人证书。

使用Python,您可以使用oauth2client库来获取这样一对的凭证对象:SignedJwtAssertionCredentials。您为SMTP服务提供范围"https://mail.google.com"

在Google的OAuth2 with Python直播文档中对此进行了解释,除了示例中假设您已经安装了“已安装的应用”,并且您将使用网络流来提示用户授权从他们的帐户发送电子邮件。

在我的情况下,这来自我自己的帐户,所以我已经设置了一个服务帐户,并附有一个私人证书,我可以使用该证书来授权凭证。

这个Python脚本演示了这个问题:

import httplib2
import smtplib
import base64
import datetime

from oauth2client.client import SignedJwtAssertionCredentials

http = httplib2.Http()

google_user = "some-account@developer.gserviceaccount.com"
google_cert = open('some-private-cert.p12', 'rb').read()

credentials = SignedJwtAssertionCredentials(
    google_user, google_cert,
    scope='https://mail.google.com/',
)

credentials.refresh(http)

# To demonstrate that we've got a valid access token, let's make a
# couple of assertions:
#
# 1. The credentials have been refreshed:
assert credentials.access_token is not None
#
# 2. The access token hasn't expired (and isn't about to):
assert (credentials.token_expiry - datetime.datetime.utcnow()).total_seconds() > 60

auth_string = 'user=%s\1auth=Bearer %s\1\1' % (
    google_user, credentials.access_token
)

smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.ehlo()

# Now, authenticate (but this fails):
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))

错误响应是(base64-decoding):

{"status":"400",
 "schemes":"Bearer",
 "scope":"https://mail.google.com/"}

我不知道它应该有效,但我不知道为什么不这样做。

0 个答案:

没有答案
相关问题