【发布时间】: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