2

我只是想为 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--

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

我在这里想念什么?

4

3 回答 3

5

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

我是怎么想出来的: https ://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md

于 2018-12-06T18:53:07.813 回答
3

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'
  }
};
...

我希望这可以帮助你!

于 2017-12-12T20:12:58.513 回答
0
const msgConfig = {
  to: email,
  from: mailConfig.defaults.from,
  templateId: mailConfig.templates.registrationConfirmation,
};

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

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

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

于 2017-12-12T08:49:13.960 回答