简体   繁体   中英

Accessing the gmail API with delegated domain-wide authority

I have a gmail account in my g-suite organization for which I want to automatically read its gmail messages. Since this needs to be run periodically with an automated process, the regular OAuth flow is not useful, since someone needs to open a browser and give permission to the automated access.

So far I've created a service account with domain-wide authority, as documented here .

The code I am using is:

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()

But I get a 400 Bad Request error:

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">

Is it possible at all to access a specific gmail account without having to grant permission from the browser? Do I need to perform any special step first? Or, is there any way get more information for debugging?

根据文档 ,您需要使用delegated_credentials = credentials.create_delegated('user_to_impersonate@mycompany.com')而不是delegated_credentials = credentials.create_delegated('myproject@myproject-123456.iam.gserviceaccount.com')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM