首页 文章

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

提问于
浏览
1

我正在按照本教程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 回答

  • 0

    将服务帐户视为虚拟用户 . 它有一个谷歌驱动器帐户谷歌日历帐户 . 我不知道的是有一个Gmail帐户 .

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

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

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

    另外,你需要考虑使用Oauth2来访问gmail .

相关问题