我已经按照代码要求创建了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='[email protected]',
to_emails='[email protected]',
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)
它引发此错误:
Traceback (most recent call last):
File "sendgrid_email.py", line 18, in <module>
print(e.message)
AttributeError: "ForbiddenError" object has no attribute "message"
并且在打印异常时显示pylint警告-
Instance of "Exception" has no "message" member
关于我做错了什么或我想念什么的任何想法吗?
另外,to_emails
只有一个电子邮件地址,我们如何附加多个收件人?
授予API密钥完全访问权限,请按照以下步骤操作:
将您的域列入白名单,请按照以下步骤操作:
注意:添加记录时,请确保主机中没有域名。裁剪出来。
如果您不想对域进行身份验证,则也可以尝试使用“单个发件人验证”。
注意:记录可能需要一些时间才能开始起作用。
如果您使用的是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="[email protected]",
to_emails=("[email protected]", "[email protected]"),
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)
to_emails
可以接收多个收件人的元组。例如
to_emails=("[email protected]", "[email protected]"),
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句