【问题标题】:Sendgrid resulting in an error 401 UnauthorizedSendgrid 导致错误 401 Unauthorized
【发布时间】:2022-10-20 20:45:15
【问题描述】:

我的代码运行每 1 小时发送一次电子邮件的脚本。 该脚本运行良好,直到 Sendgrid 导致错误 HTTP 401 Unauthorized。 我在网上查了一下,发现这可能是由于错误的 API 密钥或在 python 代码中没有正确导入 API。但到目前为止,我的代码运行良好。

sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
def send_mail(to_email, subject, message, from_email=To("fromemail@id")):
    """
    Input : to_email_list , subject , message string , from_email
    Action: sends mail to all the recipients mentioned in the to_ids list

    """

    try:

        content = Content("text/html", message)
        mail = Mail(from_email, to_email, subject, content)
        mail_json = mail.get()
        print("MAIL JSON", mail_json)

        response = sg.client.mail.send.post(request_body=mail_json)
        print(response.headers)
        print("response code :", response.status_code)
        print(
            content,
        )

        return True

    except Exception as e:
        print(e)
        return False



send_mail_utils.send_mail('toemail','testing','This is the message')

我尝试了以下方法:

  1. sendgrid.SendGridAPIClient(API)中直接传递api token id
  2. 使用新的 API 令牌

【问题讨论】:

  • 您在哪里运行此代码 - 在托管服务或本地计算机上?我建议尝试从另一台设备运行它,或者直接从 REPL 运行它来测试 API 密钥。

标签: python sendgrid


【解决方案1】:

我认为这不是 SendGrid API 问题。这可能是因为您没有正确导入SENDGRID_API_KEY

仅用于测试,请尝试使用硬编码的密钥 p.e. SENDGRID_API_KEY="xpto123,而不是方法os.environ.get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2018-07-27
    • 2018-04-01
    • 1970-01-01
    • 2022-06-29
    • 2017-05-14
    相关资源
    最近更新 更多