对于具有委派域访问权限的正确配置的服务帐户,gmail api http连接失败

时间:2015-07-01 14:34:53

标签: python http gmail google-api-python-client service-accounts

我正在尝试通过python API连接到我的gmail收件箱。 我有一个连接到目录api的工作示例来执行设置的用户维护操作,并且几乎与此代码的工作方式相同。所以我已经浏览了我的服务帐户用户的所有开发控制台和安全设置,他们有一个电子邮箱,里面有一封测试邮件,等待我用这段代码阅读。目前,我的问题是:

gmail_service = build('gmail', 'v1', http=http)
抛出:
File "./gmail_test.py", line 29, in <module> gmail_service = build('gmail', 'v1', http=http) NameError: name 'http' is not defined

不太确定我缺少什么,因为为管理员sdk访问量身定制的几乎完全相同。

无论如何,这是代码:

import urllib2
from httplib2 import Http
from googleapiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

client_email = '<private>@developer.gserviceaccount.com'
with open("Unsubscribe Processing.p12") as f:
    private_key = f.read()

creds = SignedJwtAssertionCredentials(
    client_email,
    private_key,
    {
    'https://www.googleapis.com/auth/gmail.readonly'
    },
    sub='serviceaccount@ourdomain.com')

auth = creds.authorize(Http())

gmail_service = build('gmail', 'v1', http=http)

results = gmail_service.users().labels().list(userId='serviceaccount@ourdomain.com').execute()
labels = results.get('labels', [])

if not labels:
    print 'No labels found.'
else:
    print 'Labels:'
    for label in labels:
        print label['name']


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

您还没有定义变量http是什么。

https://developers.google.com/gmail/api/auth/web-server开始,这似乎是您创建Gmail服务对象的方式:

http = httplib2.Http()
http = creds.authorize(http)
gmail_service = build('gmail', 'v1', http=http)