【问题标题】:Get mail from gmail using service account使用服务帐户从 gmail 获取邮件
【发布时间】:2018-05-18 07:15:45
【问题描述】:

我正在使用 google 服务帐户从没有 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()

【问题讨论】:

  • 我认为您的实施不适用于服务帐户,因为您使用的是“自己的帐户”,而不是服务帐户。在这里查看代码示例gmail_service_account_api 作为参考。
  • 但是当我调用execute() 方法时,为什么谷歌配额显示使用API​​ 图表。它还显示了我在配额中从此代码调用的 API。你能告诉我如何在没有 UI 的情况下获取我的电子邮件吗?我在服务器上有 cron,它将从 gmail 读取我的电子邮件。有什么想法吗?
  • 我不使用 cron
  • 好的。 NP,但是有什么想法可以在没有 UI 的情况下获取电子邮件?

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


【解决方案1】:

自从这篇文章第一次写出来之后发生了很大的变化,

如果其他人仍在寻找答案。这是我今天对 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()

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

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 2021-09-29
    • 2015-07-10
    • 2017-11-14
    • 2021-03-15
    • 2020-09-30
    • 2021-12-16
    • 2020-11-01
    • 2013-11-17
    相关资源
    最近更新 更多