python-2.7 - 403 "Request had insufficient authentication scopes"使用 Python 在 Google API 中创建草稿时

标签 python-2.7 gmail-api

我是第一次使用 google api,一般来说我是编码新手,有一个我确信很简单的问题,但我找不到答案。当我运行以下代码时 -

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

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'])


message_body = "This is the message"

message = {'message': message_body}

draft = service.users().drafts().create(userId='me', body=message).execute()

我能够成功地在我的 Gmail 帐户中列出标签,但是创建草稿的请求会退回错误消息“请求的身份验证请求不足”。我发现创建草稿需要以下范围之一:
  • https://mail.google.com/
  • https://www.googleapis.com/auth/gmail.modify
  • https://www.googleapis.com/auth/gmail.compose

  • 但对于我的生活,我无法弄清楚这究竟意味着什么或如何实现它,尽管我已尽力在某处找到它。

    最佳答案

    您可能有一个全局变量 SCOPES在您的代码中,值为 https://www.googleapis.com/auth/gmail.readonly如果您正在关注快速入门。当您的用户被重定向到 Google 以便为您提供 access_token 时,将使用这些范围。这样您就可以阅读您用户的 Gmail 帐户的内容。

    为了发送草稿等,您需要您提到的范围之一,例如https://mail.google.com/ .更改您的值 SCOPES到此字符串,并删除位于 ~/.credentials/gmail-python-quickstart.json 的凭据正如 the Quickstart 所概述的为了获得新的凭证,这些凭证不仅可以读取内容,还可以做更多的事情。

    关于python-2.7 - 403 "Request had insufficient authentication scopes"使用 Python 在 Google API 中创建草稿时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186856/

    相关文章:

    python - 将字符串转换为有序字典?

    python - 如何使用 Gmail API `insert` `full` 格式的邮件?

    python - 将 python for 循环的一次迭代的输出通过管道传输到另一个脚本

    node.js - meteor 中的 gmail 发送 api 失败,错误代码为 400

    javascript - Gmail API User.Message 属性不起作用

    python - 使用 Google Gmail API 进行桌面应用程序

    php - 使用 PHP 的 Gmail 推送通知

    python-2.7 - pyspark shell 未以伪分布式模式启动

    python-2.7 - 属性错误: 'NoneType' object has no attribute 'encode' in python 2. 7

    python - Beautiful Soup 将 Unicode 字符转换为 HTML 实体