Gmail API 服务器到服务器应用程序(错误请求错误)

Posted

技术标签:

【中文标题】Gmail API 服务器到服务器应用程序(错误请求错误)【英文标题】:Gmail API server to server application (Bad Request error) 【发布时间】:2017-07-02 12:25:06 【问题描述】:

我正在关注本教程Using OAuth 2.0 for Server to Server Applications。我正在尝试使用服务帐户连接到 Gmail API。

我最终得到的代码如下所示:

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
import json

scopes = ['https://www.googleapis.com/auth/gmail.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name('******.json', scopes)

http_auth = credentials.authorize(Http())
service = build('gmail', 'v1', http=http_auth)
request = service.users().messages().list(userId='me')
response = request.execute()

print json.dumps(response, sort_keys=True, indent=2)

但是,当我运行此代码时,我收到以下错误:

googleapiclient.errors.HttpError:https://www.googleapis.com/gmail/v1/users/me/messages?alt=json 返回“错误请求”>

有人可以帮助我了解此错误的来源吗?

【问题讨论】:

【参考方案1】:

将服务帐户视为虚拟用户。它有一个 Google Drive 帐户和一个 Google 日历帐户。据我所知,它没有一个 Gmail 帐户。

通常,当您使用服务帐号请求数据时,您必须手动授予服务帐号访问该数据的权限。在谷歌驱动器的情况下,您可以与服务帐户共享一个文件夹,使其能够访问谷歌驱动器。 (您也可以上传到它的驱动器帐户,但这超出了这个问题的范围)

无法授予其他用户访问您的 Gmail 帐户的权限,因此无法将服务帐户与普通用户的 Gmail 帐户一起使用。

注意:如果这不是普通用户的 Gmail 帐户,实际上是基于 google 域的帐户,那么您可以通过管理部分授予服务帐户访问域中其他用户的所有电子邮件的权限。

否则,您需要考虑使用 Oauth2 访问 gmail。

【讨论】:

以上是关于Gmail API 服务器到服务器应用程序(错误请求错误)的主要内容,如果未能解决你的问题,请参考以下文章

Gmail API - PHP - 使用服务帐户发送电子邮件

访问 Gmail API 时出现错误请求

如何在客户端启动 GMAIL Api 身份验证? [复制]

发布到 Gmail API 时出现 http 500 后端错误

Gmail REST API:400错误请求+失败的前提条件

尝试使用服务帐户读取 GMAIL 时出现错误代码 400