本文介绍了使用 gmail API (python) 发送电子邮件时出现 403 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 中的 Gmail API 发送电子邮件.我想我遵循了相关文档和 YouTube 视频.

我遇到了这个错误:

googleapiclient.errors.HttpError: HttpError 403 请求 https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json 时返回权限不足"

这是我的脚本:

#!/usr/bin/env python从 googleapiclient.discovery 导入构建从 httplib2 导入 Http从 oauth2client 导入文件、客户端、工具从 email.mime.text 导入 MIMEText导入 base64导入错误范围 = 'https://mail.google.com/'CLIENT_SECRET = 'client_secret.json'store = file.Storage('storage.json')credz = store.get()如果不是 credz 或 credz.invalid:标志 = tools.argparser.parse_args(args=[])流 = client.flow_from_clientsecrets(CLIENT_SECRET, SCOPES)credz = tools.run_flow(flow, store, flags)GMAIL = build('gmail', 'v1', http=credz.authorize(Http()))def CreateMessage(sender, to, subject, message_text):"""为电子邮件创建消息.参数:发件人:发件人的电子邮件地址.to:收件人的电子邮件地址.主题:电子邮件的主题.message_text:电子邮件消息的文本.返回:一个包含 base64url 编码的电子邮件对象的对象."""消息 = MIMEText(message_text)消息['至'] = 至消息['来自'] = 发件人消息['主题'] = 主题返回 {'raw': base64.urlsafe_b64encode(message.as_string())}def SendMessage(service, user_id, message):"""发送电子邮件.参数:service:授权的 Gmail API 服务实例.user_id:用户的电子邮件地址.特殊值我"可用于指示经过身份验证的用户.消息:要发送的消息.返回:发送消息."""尝试:消息 = (service.users().messages().send(userId=user_id, body=message).执行())打印 '消息 ID:%s' % 消息 ['id']回信除了errors.HttpError,错误:打印 '发生错误:%s' % 错误message = CreateMessage('[email protected]', '[email protected]', 'test_subject', 'foo')打印信息SendMessage(GMAIL,'我',消息)

我尝试添加范围、尝试不同的电子邮件等.我也通过登录浏览器进行了身份验证.(顺便说一下,[email protected] 是一个虚拟电子邮件)

解决方案

尝试删除生成的 storage.json 文件,然后重试.

您可能正在尝试使用不同范围的此脚本,因此storage.json"可能包含错误的详细信息.

I'm trying to send an email using the Gmail API in python. I think I followed the relevant documentation and youtube vids.

I'm running into this error:

googleapiclient.errors.HttpError: HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Insufficient Permission"

Here is my script:


    #!/usr/bin/env python

    from googleapiclient.discovery import build
    from httplib2 import Http
    from oauth2client import file, client, tools
    from email.mime.text import MIMEText
    import base64
    import errors

    SCOPES = 'https://mail.google.com/'
    CLIENT_SECRET = 'client_secret.json'

    store = file.Storage('storage.json')
    credz = store.get()
    if not credz or credz.invalid:
        flags = tools.argparser.parse_args(args=[])
        flow = client.flow_from_clientsecrets(CLIENT_SECRET, SCOPES)
        credz = tools.run_flow(flow, store, flags)

    GMAIL = build('gmail', 'v1', http=credz.authorize(Http()))

    def CreateMessage(sender, to, subject, message_text):
      """Create a message for an email.

      Args:
        sender: Email address of the sender.
        to: Email address of the receiver.
        subject: The subject of the email message.
        message_text: The text of the email message.

      Returns:
        An object containing a base64url encoded email object.
      """
      message = MIMEText(message_text)
      message['to'] = to
      message['from'] = sender
      message['subject'] = subject
      return {'raw': base64.urlsafe_b64encode(message.as_string())}

    def SendMessage(service, user_id, message):
      """Send an email message.

      Args:
        service: Authorized Gmail API service instance.
        user_id: User's email address. The special value "me"
        can be used to indicate the authenticated user.
        message: Message to be sent.

      Returns:
        Sent Message.
      """
      try:
        message = (service.users().messages().send(userId=user_id, body=message)
                   .execute())
        print 'Message Id: %s' % message['id']
        return message
      except errors.HttpError, error:
        print 'An error occurred: %s' % error

    message = CreateMessage('[email protected]', '[email protected]', 'test_subject', 'foo')
    print message
    SendMessage(GMAIL, 'me', message)

I tried adding scopes, trying different emails, etc. I have authenticated by logging into my browser as well. (The [email protected] is a dummy email btw)

解决方案

Try deleting generated storage.json file and then try again afresh.

you might be trying this script with different scopes so "storage.json" might be having wrong details.

这篇关于使用 gmail API (python) 发送电子邮件时出现 403 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:22