如何替换Sendgrid模板变量? (在node-js中)

时间:2017-11-04 15:19:22

标签: javascript node.js email templates sendgrid

这似乎是一个我不知道的简单参数,但我无法弄清楚究竟是什么。

这是我发送的请求' @ sendgrid / mail':

email.js:

const sgMail = require('@sendgrid/mail');

function emailRequest() {
    msg = {
      to: 'test+10@gmail.com
      from: 'info@owner.io',
      subject: 'Receipt for Business Expenses',
      template_id: 'db6d11ae-41e4-4e1a-a71b-f5368eb21c9c',
      personalizations: [
        {
          to: 'test+10@gmail.com,
          from: 'info@ownr.io,
          subject: 'Receipt for Business Expenses,
          template_id: 'db6d11ae-41e4-4e1a-a71b-f5368eb21c9c',
          substitutions: {
            ':firstname': 'Bobba',
            ':ordernumber': 'WHAAA',
            ':orderdate': 'today',
            ':ordertime': 'NOW!',
          },
          custom_args: {
            ':firstname': 'Bobba',
            ':ordernumber': 'WHAAA',
            ':orderdate': 'today',
            ':ordertime': 'NOW!',
          },
        },
      ],
      sub: {
        ':firstname': 'Bobba',
        ':ordernumber': 'WHAAA',
        ':orderdate': 'today',
        ':ordertime': 'NOW!',
      },
      substitutions: {
        ':firstname': 'Bobba',
        ':ordernumber': 'WHAAA',
        ':orderdate': 'today',
        ':ordertime': 'NOW!',
      },
    };

  sgMail.setApiKey(process.env.SENDGRID_API_KEY);

  return sgMail
    .send(msg)
    .then(response => {
      return response;
    })
    .catch(err => {
      throw err;
    });
}

电子邮件发送,但我仍然获得未经取消的模板:

enter image description here

sendgrid-nodejs mail.js的源代码似乎表示,只要有替换&#39;,它就会使用这些替换来初始化邮件类,但它不起作用:< / p>

https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/helpers/classes/mail.js

https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html

如何正确地将变量替换为模板?我使用了错误的包吗?

1 个答案:

答案 0 :(得分:8)

经过一番挖掘后,我在他们的github的问题部分找到了答案。我错过了'substitutionWrappers'。为了使它工作,我所要做的就是在消息中添加'substitutionWrappers'以及'替换':

const msg = {
    to: 'test@email.com'
    from: 'info@gmail.io',
    subject: 'Receipt for Business Expenses',
    template_id: 'da6db3ae-41e4-4e1a-a71b-f5368ab41c9c',
    substitutionWrappers: [':', ''],
    substitutions: {
      firstname: 'Bobba',
      ordernumber: 'WHAAA',
      orderdate: 'today',
      ordertime: 'NOW!',
    },
  };