SuperAPI AI 工具集

twilio-sendgrid-email-send

营销与增长

查看项目

更新于 10-15 16:25

技能介绍

用途

该技能用于通过 SendGrid v3 Mail Send API 发送事务性邮件和批量邮件。所有邮件发送都通过 POST /v3/mail/send 完成,该端点返回 202 Accepted(已排队),而非 200 OK(已送达)。送达确认通过 Event Webhook 异步获取。

代理安全

发送前始终与用户确认收件人、主题和内容。邮件一旦送达即不可撤销。未经用户明确批准,切勿自主发送邮件,尤其是向多个收件人批量发送时。代表用户发送邮件时,始终回报已发送的内容——收件人、主题和 API 响应状态码。为所有发送维护应用级审计日志。

主要能力

基本发送

Python 示例:

import os, sendgrid
from sendgrid.helpers.mail import Mail

sg = sendgrid.SendGridAPIClient(os.environ["SENDGRID_API_KEY"])
message = Mail(
    from_email="verified@yourdomain.com",
    to_emails="recipient@example.com",
    subject="Order Confirmation",
    html_content="Your order #1234 is confirmed."
)
response = sg.send(message)
print(f"Status: {response.status_code}")  # 202 = queued

Node.js 示例:

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const [response] = await sgMail.send({
    to: "recipient@example.com",
    from: "verified@yourdomain.com",
    subject: "Order Confirmation",
    html: "<p>Your order #1234 is confirmed.</p>",
});
console.log(`Status: ${response.statusCode}`); // 202 = queued

使用动态模板的个性化批量发送

动态模板使用 Handlebars 语法。模板 ID 以 d- 开头。在 SendGrid Console > Email API > Dynamic Templates 中创建模板。

Python 示例:

from sendgrid.helpers.mail import Mail, To

message = Mail(
    from_email="noreply@yourdomain.com",
    to_emails=[
        To("alice@example.com", dynamic_template_data={"name": "Alice", "order_id": "123"}),
        To("bob@example.com", dynamic_template_data={"name": "Bob", "order_id": "456"}),
    ],
)
message.template_id = "d-xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
sg.send(message)

Node.js 示例:

await sgMail.send({
    from: { email: "noreply@yourdomain.com" },
    template_id: "d-xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    personalizations: [
        { to: [{ email: "alice@example.com" }], dynamic_template_data: { name: "Alice", order_id: "123" } },
        { to: [{ email: "bob@example.com" }], dynamic_template_data: { name: "Bob", order_id: "456" } },
    ],
});

同一 personalization 的 to 数组中的收件人可以看到彼此。如需私密发送,请使用单独的 personalizations(每个收件人一个)。

定时发送

最多可提前 72 小时安排发送。取消需要发送前分配的 batch ID。

Python 示例:

import time, requests

headers = {"Authorization": f"Bearer {os.environ['SENDGRID_API_KEY']}", "Content-Type": "application/json"}

# Get batch ID first
batch = requests.post("https://api.sendgrid.com/v3/mail/batch", headers=headers).json()

# Include batch_id and send_at in the message
send_at = int(time.time()) + 3600  # Unix SECONDS, not ms

# Cancel if needed (before send_at)
requests.post("https://api.sendgrid.com/v3/user/scheduled_sends",
    headers=headers,
    json={"batch_id": batch["batch_id"], "status": "cancel"})

附件

在 attachments 数组中对文件进行 Base64 编码。总限制:每个请求 30MB(编码开销前约 22MB)。

import base64
from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition

with open("invoice.pdf", "rb") as f:
    encoded = base64.b64encode(f.read()).decode()

message = Mail(from_email="billing@yourdomain.com", to_emails="customer@example.com",
               subject="Your Invoice", html_content="<p>Invoice attached.</p>")
message.attachment = Attachment(FileContent(encoded), FileName("invoice.pdf"),
                                FileType("application/pdf"), Disposition("attachment"))
sg.send(message)

分类与自定义参数

分类用于标记发送以进行分析细分(每条消息最多 10 个):

message.category = ["transactional", "order-confirmation"]

自定义参数将元数据传递到 Event Webhooks(仅限键值字符串):

message.custom_args = {"order_id": "1234", "env": "production"}

这些参数会出现在 webhook 事件负载中,使您能够将送达事件关联回应用数据。

沙箱模式(测试)

验证请求而不实际发送。返回 200 OK(而非 202)。

message.mail_settings = {"sandbox_mode": {"enable": True}}
response = sg.send(message)  # 200 = validated, not sent

限制

  • 每次 API 调用不能发送超过 1,000 个收件人——硬性限制。需拆分为多个请求。
  • 不能提前超过 72 小时安排发送——send_at 会拒绝超过 72 小时的时间戳。
  • 处理开始后无法取消发送——只有预先分配了 batch ID 的定时消息才能取消。
  • send_at 不能使用毫秒——JS Date.now() 返回毫秒。需除以 1000,否则时间戳会被静默拒绝(>72h)。
  • personalizations 中的 subject 字段是纯字符串覆盖——如需动态主题,请在动态模板的 subject 字段中设置 Handlebars 变量(例如 {{{subject}}}),并通过 dynamic_template_data 传递值。personalizations 的 subject 键会完全绕过模板主题。
  • 未定义的模板变量渲染为空字符串——dynamic_template_data 键的拼写错误不会报错,属于静默失败。
  • 413 Payload Too Large 返回 nginx HTML 而非 JSON——超过 30MB 会返回 HTML 错误页。解析前请检查 Content-Type。
  • 使用 template_id 时内容为空——省略 content 字段。如果同时包含两者,template_id 优先,content 被忽略。

后续步骤

  • 账户设置与域名认证:twilio-sendgrid-account-setup
  • 模板与设置:twilio-sendgrid-email-settings
  • 通过 webhooks 跟踪送达:twilio-sendgrid-webhooks
  • 管理退信与退订:twilio-sendgrid-suppressions