SendGrid API V3中HTML模板substitutions变量替换失效问题求助
SendGrid HTML邮件变量替换失效问题
问题情况
我照着官方文档写了个极简示例,结果HTML里的变量替换完全没生效。
我的代码:
import dotenv from "dotenv"; import sgMail from "@sendgrid/mail"; (async () => { dotenv.config(); sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'test99@gmail.com', from: 'sender@example.com', subject: 'Welcome to Our Newsletter', html: '<html><head></head><body><p>Hello {{name}},</p><p>Thank you for signing up for our newsletter!</p></body></html>', substitutions: { '{{name}}': 'John Doe' // 想把{{name}}换成收件人名字 }, }; // @ts-ignore sgMail.send(msg) .then(() => { console.log('邮件发送成功'); }) .catch((error) => { console.error('邮件发送失败:', error); }); })();
收到的邮件内容:
Hello {{name}},
Thank you for signing up for our newsletter!
解决办法
1. 用动态模板(官方推荐)
这是最可靠的方式:
- 先去SendGrid后台创建一个动态模板,把你的HTML内容放进模板里,变量保持
{{name}}。 - 代码里删掉
html字段,换成templateId填你创建的模板ID,变量放到dynamicTemplateData里:
const msg = { to: 'test99@gmail.com', from: 'sender@example.com', subject: 'Welcome to Our Newsletter', templateId: '你的模板ID', // 替换成实际模板ID dynamicTemplateData: { name: 'John Doe' }, };
2. 手动替换变量
如果不想用动态模板,直接在代码里自己替换HTML里的变量就行:
const userName = 'John Doe'; // 直接用模板字符串替换变量 const htmlContent = `<html><head></head><body><p>Hello ${userName},</p><p>Thank you for signing up for our newsletter!</p></body></html>`; const msg = { to: 'test99@gmail.com', from: 'sender@example.com', subject: 'Welcome to Our Newsletter', html: htmlContent, };
3. 修正substitutions用法(不推荐)
要是非得用SendGrid自带的替换,得改两处:
substitutions里的键名去掉{{}},直接写name;- 确保你的SendGrid账号开启了内容替换功能。
代码调整后:
substitutions: { name: 'John Doe' // 这里不用带{{}} }
不过这种方式不如动态模板稳定,官方更建议用动态模板。
内容的提问来源于stack exchange,提问作者Peter Kellner
相关产品推荐
相关产品推荐

