我已经按照代码要求创建了一个API Key,并在环境中添加了它。以下是我正在使用的代码,并按照提供的步骤进行了操作。这里。
# 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"
而当 打印异常 它显示幽林警告-
Instance of "Exception" has no "message" member
有什么想法吗,我做错了什么,或者我缺少什么?
还有 to_emails
是只有一个电子邮件地址。我们如何附加多个收件人?
给予API Key完整的访问权限,按照步骤操作。
将您的域名加入白名单,按照步骤操作。
注意:添加记录时,一定不要把主机中的域名。裁剪掉。
如果你不想验证域名,你可以尝试用 单一发送方验证 也是。
注意:记录可能需要一些时间才能开始运作。
如果你使用的是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]"),