[英]Insufficient Permission to modify Gmail labels with via API
我正在嘗試通過其API修改Gmail收件箱。
但是我得到了錯誤:
請求https://www.googleapis.com/gmail/v1/users/me/labels/SOME_MESSAGE_ID時出現HttpError錯誤,返回“權限不足”
我使用相同的OAuth憑據下載郵件。 所以我知道這是有效的。
我檢查標簽范圍是否可用。
我看不到其他任何我做錯的事情。 標簽文檔無濟於事。
有什么可以說明的嗎?
def archive(msg_id):
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', ArchiveScope)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
msg_labels = {'removeLabelIds': ['INBOX'], 'addLabelIds': ['MyLabel']}
service.users().labels().update(userId='me', id=msg_id, body=msg_labels).execute()
print('Message ID: %s' % msg_id)
您的代碼有些錯誤。 首先,確保ArchiveScope
是一個包含應用程序所需范圍的列表。 為了更新,創建或刪除Gmail標簽,無論是https://www.googleapis.com/auth/gmail.readonly
或https://www.googleapis.com/auth/gmail.labels
就足夠了, 因為這里記錄 。
您的代碼建議您嘗試刪除“ INBOX”標簽,並添加一個名為“ MyLabel”的新標簽。 service.users().labels().update()
描述的方法只能用於更改GMail帳戶上現有標簽的信息,而不能創建或刪除。 最重要的是,“收件箱”標簽是保留標簽,不能刪除-當發出刪除該標簽的有效請求時,服務器將收到“無效的刪除請求”,如下所示。
DELETE https://www.googleapis.com/gmail/v1/users/me/labels/INBOX
{
"error": {
"code": 400,
"message": "Invalid delete request",
"errors": [
{
"domain": "global",
"message": "Invalid delete request",
"reason": "invalidArgument"
}
]
}
}
但是,可以使用service.users().messages().modify()
和{'removeLabelIds': ['INBOX'], 'addLabelIds': ['MyLabel']}
請求正文刪除單個郵件的“收件箱”標簽您以前使用過的 。 這只會從指定的消息中刪除標簽,但是不會完全刪除標簽。
可以在此處找到用於修改現有標簽內容的完整文檔,但是id參數應等於您要編輯的標簽的唯一ID,並且正文有效負載應為包含您想要的新名稱的字典結構。將標簽更改為:
lbl_id = "Label_XXXXXXXXXXXXXXX"
msg_labels = {
'name' : [‘newLabelName’]
}
service.users().labels().update(userId='me', id=lbl_id, body = msg_labels).execute()
print('Message ID: %s' % lbl_id)
為了創建標簽, 您可以使用具有相同作用域的service.users().labels().create(userId='me', body={'name' : 'MyLabel' }).execute()
函數作為update()。 由於尚未創建標簽,因此不需要標簽ID。
刪除標簽是一樣的,盡管service.users().labels().delete(userId='me').execute()
無需正文即可使用。 與create()不同, 刪除服務確實需要標簽ID ,但是此請求不會返回響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.