gpt4 book ai didi

python - 使用全域授权访问 gmail API

转载 作者:行者123 更新时间:2023-11-28 18:16:17 24 4
gpt4 key购买 nike

我在我的 g-suite 组织中有一个 gmail 帐户,我想自动读取它的 gmail 邮件。由于这需要通过自动化流程定期运行,因此常规 OAuth 流程没有用,因为需要有人打开浏览器并授予自动访问权限。

到目前为止,我已经创建了一个具有全域权限的服务帐户,如 here 所述。

我使用的代码是:

import httplib2
from apiclient import discovery

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', ]
CLIENT_SECRET_FILE = '/path/to/client_secrets.json'


def get_credentials():
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, SCOPES)
delegated_credentials = credentials.create_delegated('myproject@myproject-123456.iam.gserviceaccount.com')
return delegated_credentials


def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

results = service.users().messages().list(userId='user_to_impersonate@mycompany.com').execute()


if __name__ == '__main__':
main()

但我收到 400 Bad Request 错误:

Traceback (most recent call last):
File "gmail.py", line 77, in <module>
main()
File "gmail.py", line 65, in main
results = service.users().messages().list(userId='user_to_impersonate@mycompany.com').execute()
File "/usr/local/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/user_to_impersonate%40mycompany.com/messages?alt=json returned "Bad Request">

是否可以在无需浏览器授权的情况下访问特定的 gmail 帐户?我需要先执行任何特殊步骤吗?或者,有什么方法可以获得更多调试信息?

最佳答案

基于 the docs ,您需要使用 delegated_credentials = credentials.create_delegated('user_to_impersonate@mycompany.com') 而不是 delegated_credentials = credentials.create_delegated('myproject@myproject-123456. iam.gserviceaccount.com').

关于python - 使用全域授权访问 gmail API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com