![](/img/trans.png)
[英]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.