sendgrid替换不起作用

时间:2017-11-19 15:28:54

标签: sendgrid sendgrid-templates

我只是想为SendGrid设置试用版电子邮件,这是我第一次使用它,所以我确信这很简单,但我似乎无法取代占位符数据。

我正在使用这样的NodeJS库:

sgMail.setApiKey(mailConfig.apiKey);

const msgConfig = {
  to: email,
  from: mailConfig.defaults.from,
  templateId: mailConfig.templates.registrationConfirmation,
  substitutions: {
    '--displayName--': original.displayName,
    '--companyName--': 'Hello world'
  }
};

console.log('Sending: ', msgConfig);

// now send the registration confirmation email.
return sgMail.send(msgConfig).then(() => {
  console.log('done.');
})
.catch((err) => {
  console.error(JSON.stringify(err));
});

在模板中有一个我使用可视化编辑器添加的文本块:

Hello --displayName--

We would love to take this opportunity to welcome you to the store.

from

--companyName--

但是,当我运行测试发送电子邮件时,它会发送邮件,但不会替换占位符。

我在这里缺少什么?

3 个答案:

答案 0 :(得分:2)

在Sendgrid文档中并不清楚,但我认为它缺少这一行:

sgMail.setSubstitutionWrappers('--', '--'); // Configure the substitution tag wrappers globally
  

然后删除替换对象键

中的短划线

请看这个链接:Sendgrid

所以,你的代码应该是:

sgMail.setApiKey(mailConfig.apiKey);

// Configure the substitution tag wrappers globally
sgMail.setSubstitutionWrappers('--', '--');

const msgConfig = {
  to: email,
  from: mailConfig.defaults.from,
  templateId: mailConfig.templates.registrationConfirmation,
  substitutions: {
    'displayName': original.displayName,
    'companyName': 'Hello world'
  }
};
...

我希望这可以帮到你!

答案 1 :(得分:1)

尝试将“替代”更改为“ dynamicTemplateData”。看起来他们在新版本中更改了名称。

我怎么知道的: https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md

答案 2 :(得分:-1)

const msgConfig = {
  to: email,
  from: mailConfig.defaults.from,
  templateId: mailConfig.templates.registrationConfirmation,
};

msgConfig.addSubstitution('%displayName%', 'Something to display');

当你有尖括号<%...%>时,似乎用户给定的变量不起作用在它们周围,这些是为<%body%>保留的。和<%subject%>标签

所以现在你可以制作看起来像这样的模板 - %displayName%