要遍历数组以发送Sendgrid事务邮件模板,您可以使用循环结构(如for循环)遍历数组,并在每次迭代中发送邮件模板。
以下是一个示例代码,展示了如何使用Sendgrid发送邮件模板:
import sendgrid
from sendgrid.helpers.mail import Mail
# 定义Sendgrid API密钥
SENDGRID_API_KEY = 'your_sendgrid_api_key'
# 定义邮件模板ID
TEMPLATE_ID = 'your_template_id'
# 定义收件人数组
recipients = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com']
# 创建Sendgrid客户端
sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)
# 遍历收件人数组
for recipient in recipients:
# 创建邮件对象
mail = Mail(
from_email='your_email@example.com',
to_emails=recipient,
)
# 设置邮件模板ID
mail.template_id = TEMPLATE_ID
# 发送邮件
response = sg.send(mail)
# 检查发送结果
if response.status_code == 202:
print(f"邮件成功发送至{recipient}")
else:
print(f"发送邮件至{recipient}时出错:{response.body}")
请确保替换代码中的以下变量:
SENDGRID_API_KEY
:您的Sendgrid API密钥。您可以在Sendgrid网站上创建一个API密钥。TEMPLATE_ID
:您的邮件模板ID。您可以在Sendgrid网站上创建一个模板,并获取其ID。recipients
:您的收件人数组。将收件人的电子邮件地址添加到列表中。此代码将遍历收件人数组,并使用Sendgrid发送邮件模板到每个收件人。发送结果将打印到控制台。