Sendgrid引入引发禁止的错误

2024-05-16 04:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行Sendgrid的intro material for Python,但是执行示例代码会抛出403禁止的错误

我采取的步骤:

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

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

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

我尝试过的事情:

  • 在那个例子中,我试着切换邮件的收发,但结果没有改变
  • 我也尝试了相同的流程,但使用了NodeJS,但结果相同

你知道我做错了什么吗


Tags: 代码pyapi示例formain错误密钥
1条回答
网友
1楼 · 发布于 2024-05-16 04:34:11

为API密钥提供完全访问权限,请执行以下步骤:

  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属性是由pylinter无法访问的sendgrid动态生成的,因为它在运行前不存在

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

# pylint: disable=no-member

E1101是no-member的代码,更精细here

# 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)

相关问题 更多 >