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

SendGrid API v3 substitutions功能失效问题求助

SendGrid API v3 替换(Substitutions)功能失效排查解决

问题根源分析

你的代码存在两个核心错误,直接导致替换功能不生效:

1. 替换变量的键格式错误

你已经通过sgMail.setSubstitutionWrappers("{{", "}}");指定了占位符的包装器,这意味着substitutions对象的键只需写变量名(比如"name"),SDK会自动为其添加{{}}包装器去匹配邮件内容里的占位符。

但你在调用时给substitutions的键额外套了一层{{}}:

substitutions: {
  "{{name}}": "John", // 错误:多添加了包装器
}

这会导致SDK最终尝试匹配{{{{name}}}},自然找不到内容里的{{name}},替换逻辑无法触发。

2. HTML内容的MIME类型错误

代码中添加HTML内容时使用了无效的MIME类型plain/html:

msg.content.push({
  type: "plain/html", // 错误:无效的MIME类型
  value: bodyHtml,
});

正确的HTML内容MIME类型应为text/html,SendGrid无法识别plain/html,会忽略该内容的替换逻辑。

额外优化点

调用函数时同时传递了顶层to参数和personalizations里的to,会造成配置冲突,建议去掉顶层to,仅在personalizations中指定收件人,保持配置一致性。

修正后的代码片段

修正substitutions的键格式

await sendEmail({
  // 移除顶层to参数
  from: "Some Service <noreply@someservice.com>",
  subject: "This is a test email",
  bodyText: `Hello {{name}}!`,
  bodyHtml: `Hello {{name}}!`,
  personalizations: [
    {
      to: "john@somemail.com",
      substitutions: {
        "name": "John", // 仅保留变量名
      },
    }
  ],
});

修正HTML内容的MIME类型

if (bodyHtml) {
  msg.content.push({
    type: "text/html", // 使用正确的MIME类型
    value: bodyHtml,
  });
}

验证效果

修正后重新调用,SendGrid会正确识别{{name}}占位符并替换为John,邮件内容将显示为Hello John!。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:26:20