Sendgrid的示例代码出现问题,如何向多个收件人发送电子邮件?

4
我已按代码要求创建了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)

它抛出了这个错误:

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只有一个电子邮件地址,我们如何附加多个收件人?

1个回答

6

为API Key授予完全访问权限,请按照以下步骤操作:

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

因此,在您的文件顶部或print(e.message)行上方,您需要添加以下任一内容,它们具有相同的意思-

# pylint: disable=no-member

E1101是代表“没有成员”的代码,了解更多请点击此处

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

to_emails 可以接受一个元组,用于发送给多个收件人。例如:

to_emails=("recipient1@example.com", "recipient2@example.com"),

1
哇,这正是我正在寻找的完美答案。谢谢! - Ambuj Bhardwaj
同样的问题,没有意识到你需要在示例中使用已列入白名单的“from_email”。还要仔细检查源计算机的IP地址是否已列入“IP访问管理”部分的白名单。 - Jeff K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接