Bartosz Animucki
Bartosz Animucki

Reputation: 31

Gmail API user impersonation (Python)

I'm trying to access the Gmail API through a service account, and impersonate a user on my company's G Suite domain to change their email settings. I followed the instructions on Google's documentation page here, but the code I come up with based on that guide keeps giving me a HTTP 400: Bad Request error.

Here's my code, where I try to retrieve the labels to see if I can successfully impersonate a user:

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('[email protected]')
    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()

The script fails at the execute() method, with HTTP 400. Any ideas?

For reference, this is the error message I get from 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='[email protected]').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">

Upvotes: 2

Views: 1781

Answers (1)

Bartosz Animucki
Bartosz Animucki

Reputation: 31

I figured it out! I was trying to use the Credentials object linked to the Service Account, instead of delegated_credentials. It's fixed by changing the line:

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

to

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

Thanks for the hints! It pays to pay attention detail.

Upvotes: 1

Related Questions