python - Sendgrid 介绍抛出 Forbidden 错误
问题描述
我正在浏览 Sendgrid 的Python 介绍材料,但执行示例代码会引发 403-Forbidden 错误。
我采取的步骤:
- 按照说明创建 API 密钥和
sendgrid.env
文件。 - 使用 python 3.5 创建一个 conda 环境:
conda create -n sendgrid python=3.5
- 安装发送网格:
(sendgrid) pip install sendgrid
- 运行示例:
(sendgrid) python main.py
其中main.py
包含从上面链接的示例页面复制的确切代码。
问题:运行main.py
抛出错误HTTP Error 403: Forbidden
。
我尝试过的事情:
- 我尝试在该示例中切换电子邮件,但没有改变结果。
- 我也尝试了相同的流程,但使用了 NodeJS,但结果相同。
关于我做错了什么的任何想法?
解决方案
授予 API Key 完全访问权限,请按照以下步骤操作:
- 设置
- API 密钥
- 编辑 API 密钥
- 完全访问
- 更新
将您的域列入白名单,请执行以下步骤:
- 设置
- 发件人身份验证
- 域认证
- 选择 DNS 主机
- 输入您的域名
- 复制所有记录并将它们放入您的高级 DNS 管理控制台
注意:添加记录时,请确保主机中没有域名。裁剪出来。
如果您不想验证域,也可以尝试使用单发件人验证。
注意:记录开始运行可能需要一些时间。
如果你使用 pylinter,e.message
会说
Instance of 'Exception' has no 'message' member
这是因为message
属性是由sendgrid
pylinter 无法访问的动态生成的,因为它在运行时之前不存在。
因此,为防止这种情况,在文件的顶部或上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)
推荐阅读
- python-3.x - 检查视图是否有装饰烧瓶
- docker - windows中的linux虚拟机如何在工作站中使用GPU?
- laravel - 1 & 1 laravel 托管问题 [SQLSTATE[HY000] [1045] Access denied for user 'XXX'@'XXX' (using > password: YES)]
- python - 适用于 Raspberry Pi CM3+ 上的 Ubuntu Core 的 Python GUI 库
- java - 执行目标 org.codehaus.mojo:findbugs-maven-plugin:3.0.5:findbugs 的 findbugs 失败:Java 返回:1
- sicp - 来自 SICP Ex 的故事的寓意。1.20?
- java - 在静态子类中获取调用父类
- gcc - Gnome/msitools 构建失败并出现“未找到包 'libgsf-1'”错误
- google-cloud-sql - 从正在运行的生产 GCP SQL 服务中导出 SQL 是否安全?
- postgresql - 在 postgres 11.2 中使用光标批量收集