【发布时间】:2017-09-07 04:27:20
【问题描述】:
我正在使用 Gmail Api 在 python 中发送电子邮件,但它似乎不适用于 Python 3.4。
代码如下:
msg = MIMEText(html, 'html')
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
username = 'user@gmail.com'
CLIENT_SECRET_FILE = '/client_secret.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, SCOPES)
try:
http_auth = credentials.authorize(Http())
service = discovery.build('gmail', 'v1', http=http_auth)
gmailMsg = {'raw': base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('utf-8')}
message = (service.users().messages().send(userId = username, body = gmailMsg).execute())
错误:
<HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Bad Request">
作为记录,我为我的项目创建的凭据是非 ui 平台(服务器-服务器)的服务帐户。 我认为可能 gmailMsg 对象没有正确编码。但是当我在 Google APIs Explorer 中使用它时,你猜怎么着:它起作用了。 我能看到的唯一区别是在 Python 中,JSON 使用单引号,而在 Google APIs Explorer 中,它迫使我使用双引号。
有人推荐吗?
P/S:我尝试了以下编码选项:
base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('utf-8')
base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('ascii')
base64.urlsafe_b64encode(msg.as_string().encode('ascii')).decode('ascii')
base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8')
base64.urlsafe_b64encode(msg.as_bytes()).decode('ascii')
base64.urlsafe_b64encode(msg.as_bytes()).decode()
编辑:有趣的是,我尝试使用不需要正文的 Label Api。但我得到了同样的错误。唯一的变化是:
SCOPES = ['https://www.googleapis.com/auth/gmail.labels']
message = (service.users().labels().list(userId = username).execute())
【问题讨论】:
标签: python python-3.x gmail-api http-error bad-request