我的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帐户而无需从浏览器授予权限?我需要先执行任何特殊步骤吗?或者,有没有办法获得更多的调试信息?
答案 0 :(得分:1)
基于the docs,您需要使用delegated_credentials = credentials.create_delegated('user_to_impersonate@mycompany.com')
而不是delegated_credentials = credentials.create_delegated('myproject@myproject-123456.iam.gserviceaccount.com')
。