403 使用 python 的 gmail api 权限不足

Vin*_*nzo 3 python api gmail

我正在尝试运行 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'))
Run Code Online (Sandbox Code Playgroud)

请帮帮我好吗?

谢谢

Sou*_*daR 5

只需从运行此脚本的文件夹中删除 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/ :)