首页 > 解决方案 > 消息的未知 id

问题描述

剧本:

>     results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
>     messages = results.get('messages', [])
> 
>     if not messages:
>         print("No messages found.")
>     else:
>         print("Message snippets:")
>         for message in messages[::-1]:
>             msg = service.users().messages().get(userId='me', id=message['id']).execute()
>             print(msg['snippet'])
>             messageid = msg['id']
>             service.users().messages().delete(userId='me', id=messageid).execute()
>             break
> 
> if __name__ == '__main__':
>     main()

嘿,我希望这个程序接收我最旧的电子邮件,打印出来,然后删除这条消息。但是,我不确定 id 是什么,而且我总是遇到这样的错误:

    Message snippets:
Google Banner Hallo Gmail, willkommen bei Google. Mit Ihrem neuen Konto können Sie Google-Produkte, ‑Apps und ‑Dienste nutzen. Für den Anfang haben wir hier einige nützliche Tipps für Sie
. Konto
Traceback (most recent call last):
  File "gmail.py", line 52, in <module>
    main()
  File "gmail.py", line 48, in main
    service.users().messages().delete(userId='me', id=messageid).execute()
  File "C:\Users\25jul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\googleapiclient\_helpers.py", line 134, in
 positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\25jul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\googleapiclient\http.py", line 907, in exe
cute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/171f0100542b03d1? returned "Insufficient Permission">

谢谢你的回答,朱利叶斯

标签: pythongmail-api

解决方案


考虑到您遇到的错误Insufficient Permission,您很可能没有提供必要的范围。

为了调用Users.messages: delete你必须使用这个范围:https://mail.google.com/

您正在进行的其他调用 (listget) 限制较少,并且可以接受其他范围。这就是为什么您在尝试删除消息时特别收到错误的原因。

笔记:

  • 即使这不是问题message ID(您正在成功检索它)也不需要messageid = msg['id'](您以前使用message['id']过,您可以再次使用它)。

参考:


推荐阅读