You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SendGrid邮件模板中使用收件人邮箱作为参数

在SendGrid批量发送邮件时将收件人邮箱作为模板参数使用

你当前把所有收件人放到to数组、搭配全局dynamicTemplateData的写法,会导致所有收件人拿到的模板数据完全一致,没法单独注入每个收件人的邮箱。要实现每个收件人在模板里看到自己的邮箱,得用SendGrid的Personalizations(个性化配置)数组替代全局的to和dynamicTemplateData。

修改后的代码实现

为每个收件人生成独立的个性化配置项,在配置里注入对应的邮箱地址作为模板参数:

public async sendTransactionalMail(title: string, template_id: string, recipients: string[], template_data: any) {
    // 为每个收件人生成独立的个性化配置
    const personalizations = recipients.map(email => ({
        to: [{ email }],
        dynamicTemplateData: {
            ...template_data,
            subject: title,
            recipient: email // 将当前收件人邮箱加入模板数据
        }
    }));

    const msg = {
        from: 'email@email.com',
        templateId: template_id,
        personalizations // 使用个性化配置数组
    };

    return await mail.send(msg);
}

在模板中使用收件人邮箱

修改代码后,直接在SendGrid动态模板里用{{{recipient}}}(三个大括号表示不转义HTML,适合邮箱地址这类纯文本)或者{{recipient}}(自动转义HTML)调用即可。

注意事项

  • 每个个性化配置项可单独设置收件人、模板数据、主题等,完全独立于其他收件人
  • SendGrid API对单次请求的personalizations数组数量有上限(通常最多1000个),如果收件人数量超过限制,需要拆分请求分批发送

内容的提问来源于stack exchange,提问作者Richard Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:10:01