Get mail from gmail using service account

1.9k views Asked by At

I'm using google service account for access all mail from gmail account without UI interface but When I execute my code it giving me error

googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Bad Request">

But when i check Quotas from https://console.developers.google.com/apis/api/gmail.googleapis.com/quotas there is showing all request that I did using my python code but it always return Bad request when I execute below code.

import httplib2
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials


def get_credentials():
    scopes = ['https://mail.google.com/',
              'https://www.googleapis.com/auth/gmail.compose',
              'https://www.googleapis.com/auth/gmail.metadata',
              'https://www.googleapis.com/auth/gmail.readonly',
              'https://www.googleapis.com/auth/gmail.labels',
              'https://www.googleapis.com/auth/gmail.modify',
              'https://www.googleapis.com/auth/gmail.metadata',
              'https://www.googleapis.com/auth/gmail.settings.basic']

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'client_secret.json', scopes=scopes)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    results = service.users().labels().list(userId='me').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

There are 1 answers

0
Logner On

Much has changed since this post was first written,

If anyone else is still looking for an answer. This is my initialization process for the Gmail API today.

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'

def main():   
    # Setup for the Gmail API
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))

    # Call the Gmail API to fetch INBOX
    results = service.users().labels().list().execute()

A major difference is the use of access tokens along with credentials in my code.