[英]How do I get around HttpError 403 Insufficient Permission? (gmail api, python)
[英]403 insufficient permission for gmail api with python
我正在尝试运行 gmail API 以从特定用户获取电子邮件。 但是我总是收到以下错误:googleapiclient.errors.HttpError:https://www.googleapis.com/gmail/v1/users/me/settings/filters?alt=json 返回“权限不足”>
我已经尝试了所有不同的建议,从更改范围到在 gmail 设置中启用安全性较低的应用程序。 最后一件事是我的代码可能是错误的:
from __future__ import print_function
from googleapiclient import discovery
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Gmail API
SCOPES = 'https://mail.google.com/'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
# Call the Gmail API
# 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'])
label_id = 'mine' # ID of user label to add
filter = {
'criteria': {
'from': 'string@test.com'
}#,
#'action': {
#'addLabelIds': [label_id],
#'removeLabelIds': ['INBOX']
#}
}
result = service.users().settings().filters().create(userId='me', body=filter).execute()
print ('Created filter: %s' % result.get('id'))
请帮帮我好吗?
谢谢
只需从运行此脚本的文件夹中删除 credentials.json 文件,然后使用最终所需的范围列表重新运行脚本,例如 SCOPES = [' https://www.googleapis.com/auth/gmail.send ', ' https://www.googleapis.com/auth/gmail.labels ']。 在出现的弹出浏览器窗口中授权所需 Gmail 帐户的范围列表。 那么你应该一切都准备好了。
背景故事:您很可能通过第一次运行 run_flow() 时弹出的浏览器屏幕授权了较少许可的范围(例如只读)。 这将在您运行脚本的文件夹中创建一个名为 credentials.json 的文件。 根据您上面的脚本,不会再次重新生成这个 credentials.json。 它只是在第一次范围内冻结。 出于好奇,您可以打开并阅读credentials.json 并查找关键的“范围”。 当然,您不能在此文件中手动添加更多范围并期望更新的范围起作用。 如果有的话,必须为不同的范围集重新生成。
不相关的警告说明:尽可能避免过于宽松的范围https://mail.google.com/ :)
以上都没有解决我将电子邮件从收件箱移动到另一个“框/标签”的问题。 我不确定 gmail api 是否发生了变化,但我发现我必须将 SCOPES 行更改为所需级别,即 SCOPES= [' https://www.googleapis.com/auth/gmail.modify '],然后删除 token.pickle 文件(按此顺序)。 在这两个更改之后,我重新运行了 python 脚本。 这两个步骤导致授权网页出现,反映被授予的新权限,因此在我给出 OK 之后,重新创建一个新的 token.pickle 文件。 之后一切都按预期进行。 没有更多的 403 错误并且电子邮件移动到目标框/标签。 我发现credentials.json 文件只允许脚本访问电子邮件,但对电子邮件本身采取的操作没有任何影响。
我发现 Anton Odman 在 Medium 上题为“Gmail API 及其文档的初学者指南”的文章是 Python 和 gmail api 的最佳整体指南。
顺便说一句,另一个“问题”是创建的标签不一定是标签 ID。 我建议运行https://stackoverflow.com/a/55713119/4495318 中提到的代码,以确保获得正确的标签 ID,除了系统生成的标签外,标签 ID 和标签名称似乎不同。
在更改或添加 SCOPES 后,只需删除使用file.Storage('credentials.json')创建的 JSON 文件即可帮助您再次运行该程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.