使用服务帐户从gmail获取邮件

时间:2017-12-04 18:41:39

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

我使用谷歌服务帐户从没有UI界面的gmail帐户访问所有邮件但是当我执行我的代码时它给了我错误

  

googleapiclient.errors.HttpError:https://www.googleapis.com/gmail/v1/users/me/labels ?alt = json返回   "错误请求">

但是当我从https://console.developers.google.com/apis/api/gmail.googleapis.com/quotas检查配额时 显示我使用我的python代码执行的所有请求,但是当我执行下面的代码时,它总是返回 Bad request

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 个答案:

答案 0 :(得分:0)

自从这篇文章被首次撰写以来,发生了很多变化,

如果其他任何人仍在寻找答案。这是我今天对Gmail API的初始化过程。

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()

主要区别是在我的代码中使用访问令牌和凭据。