gpt4 book ai didi

python - Gmail API 用户模拟(Python)

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:18 26 4
gpt4 key购买 nike

我正在尝试通过服务帐户访问 Gmail API,并模拟我公司 G Suite 域中的用户来更改他们的电子邮件设置。我按照 Google 文档页面上的说明进行操作 here ,但我根据该指南提出的代码不断给我一个 HTTP 400:错误请求错误。

这是我的代码,我在其中尝试检索标签以查看我是否可以成功模拟用户:

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None

def main():


from oauth2client.service_account import ServiceAccountCredentials

#scopes = ['https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.labels','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.settings.basic ','https://www.googleapis.com/auth/gmail.settings.sharing']
scopes = ['https://mail.google.com/']

credentials = ServiceAccountCredentials.from_json_keyfile_name('/Users/bartoszanimucki/Downloads/service_secret.json', scopes)
http = credentials.authorize(httplib2.Http())

delegated_credentials = credentials.create_delegated('user@domain.com')
http_auth = credentials.authorize(httplib2.Http())

service = discovery.build('gmail', 'v1', http=http_auth)

results = service.users().labels().list(userId='me').execute()

print(results)

if __name__ == '__main__':
main()

脚本在 execute() 方法处失败,出现 HTTP 400。有什么想法吗?

作为引用,这是我从 Python 得到的错误信息:

Traceback (most recent call last):
File "sample.py", line 37, in <module>
main()
File "sample.py", line 32, in main
results = service.users().labels().list(userId='bb@comcamenergy.com').execute()
File "/Library/Python/2.7/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/http.py", line 840, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/bb%40comcamenergy.com/labels?alt=json returned "Bad Request">

最佳答案

我想通了!我试图使用链接到服务帐户的 Credentials 对象,而不是 delegated_credentials。它通过更改行来修复:

http_auth = credentials.authorize(httplib2.Http())

http_auth = delegated_credentials.authorize(httplib2.Http())

谢谢指教!注意细节是值得的。

关于python - Gmail API 用户模拟(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438902/

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