Search code examples
pythonhttpgmailgoogle-api-python-clientservice-accounts

gmail api http connection fails for properly configured service account with delegated domain access


I'm trying to get a connection to my gmail inbox via the python API. I've got a working example for connecting to the directory api to do user maintenance operations that is set up and working nearly identically to this code. So I've been through all the dev console and security setup for my service account user, who has an email box with a test email sitting in it waiting for me to read it with this code. Currently, my issue is that the line:

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

Not quite sure what I'm missing as the nearly identical tailored for admin sdk access works great.

anyway, here's the code:

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

auth = creds.authorize(Http())

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

results = gmail_service.users().labels().list(userId='[email protected]').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()

Solution

  • You haven't defined what the variable http is.

    From https://developers.google.com/gmail/api/auth/web-server, this seems to be how you create a Gmail service object:

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