Amb*_*waj 4 python twilio sendgrid
我已根据代码的要求创建了一个 API 密钥并将其添加到环境中。
以下是我正在使用的代码,并已按照此处提供的步骤进行操作。
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='from_email@example.com',
to_emails='to@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)
Run Code Online (Sandbox Code Playgroud)
它抛出这个错误:
Traceback (most recent call last):
File "sendgrid_email.py", line 18, in <module>
print(e.message)
AttributeError: "ForbiddenError" object has no attribute "message"
Run Code Online (Sandbox Code Playgroud)
在打印异常时,它显示 pylint 警告 -
Instance of "Exception" has no "message" member
Run Code Online (Sandbox Code Playgroud)
关于我做错了什么或缺少什么有什么想法吗?
另外,to_emails只有一个电子邮件地址,我们如何附加多个收件人?
授予 API Key 完全访问权限,请执行以下步骤:
将您的域列入白名单,请按照步骤操作:
注意:添加记录时,请确保主机中没有域名。将其裁剪出来。
如果您不想验证域,您也可以尝试使用单一发件人验证。
注意:记录可能需要一些时间才能开始运行。
如果你使用 pylinter,e.message会说
Instance of 'Exception' has no 'message' member
Run Code Online (Sandbox Code Playgroud)
这是因为message属性是动态生成的,sendgridpylinter 无法访问它,因为它在运行时不存在。
因此,为了防止这种情况,在文件顶部或上面print(e.message)一行,您需要添加以下任一内容,它们的含义相同 -
# pylint: disable=no-member
Run Code Online (Sandbox Code Playgroud)
E1101 是 的代码no-member,详细信息请参见此处
# pylint: disable=E1101
Run Code Online (Sandbox Code Playgroud)
现在下面的代码应该适合您。只需确保您已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)
Run Code Online (Sandbox Code Playgroud)
to_emails可以接收多个接收者的元组。例如
to_emails=("recipient1@example.com", "recipient2@example.com"),
Run Code Online (Sandbox Code Playgroud)