首页 > 解决方案 > Sendgrid 介绍抛出 Forbidden 错误

问题描述

我正在浏览 Sendgrid 的Python 介绍材料,但执行示例代码会引发 403-Forbidden 错误。

我采取的步骤:

  1. 按照说明创建 API 密钥和sendgrid.env文件。
  2. 使用 python 3.5 创建一个 conda 环境:conda create -n sendgrid python=3.5
  3. 安装发送网格:(sendgrid) pip install sendgrid
  4. 运行示例:(sendgrid) python main.py

其中main.py包含从上面链接的示例页面复制的确切代码。

问题:运行main.py抛出错误HTTP Error 403: Forbidden

我尝试过的事情:

关于我做错了什么的任何想法?

标签: pythonsendgrid

解决方案


授予 API Key 完全访问权限,请按照以下步骤操作:

  1. 设置
  2. API 密钥
  3. 编辑 API 密钥
  4. 完全访问
  5. 更新

将您的域列入白名单,请执行以下步骤:

  1. 设置
  2. 发件人身份验证
  3. 域认证
  4. 选择 DNS 主机
  5. 输入您的域名
  6. 复制所有记录并将它们放入您的高级 DNS 管理控制台

注意:添加记录时,请确保主机中没有域名。裁剪出来。

如果您不想验证域,也可以尝试使用单发件人验证

注意:记录开始运行可能需要一些时间。


如果你使用 pylinter,e.message会说

Instance of 'Exception' has no 'message' member

这是因为message属性是由sendgridpylinter 无法访问的动态生成的,因为它在运行时之前不存在。

因此,为防止这种情况,在文件的顶部或上print(e.message)一行,您需要添加以下任一内容,它们的含义相同-

# pylint: disable=no-member

E1101 是代码,这里no-member更详细

# pylint: disable=E1101

现在下面的代码应该适合你。只需确保您已SENDGRID_API_KEY在环境中设置。如果没有,您也可以直接替换它,os.environ.get("SENDGRID_API_KEY")但这不是一个好习惯。

# pylint: disable=E1101

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email="from_email@your-whitelisted-domain.com",
    to_emails=("recipient1@example.com", "recipient2@example.com"),
    subject="Sending with Twilio SendGrid is Fun",
    html_content="<strong>and easy to do anywhere, even with Python</strong>")
try:
    sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)

推荐阅读