Gmail API用户模拟(Python)

时间:2017-02-24 12:40:08

标签: python google-api

我正在尝试通过服务帐户访问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">

1 个答案:

答案 0 :(得分:1)

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

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

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

感谢您的提示!注重细节是值得的。