Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute Sendgrid template variables? (in node-js)

It seems to be a simple parameter I'm missing but I'm having trouble figuring out exactly what it is.

This is the request I'm sending with '@sendgrid/mail':

email.js:

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

function emailRequest() {
    msg = {
      to: '[email protected]
      from: '[email protected]',
      subject: 'Receipt for Business Expenses',
      template_id: 'db6d11ae-41e4-4e1a-a71b-f5368eb21c9c',
      personalizations: [
        {
          to: '[email protected],
          from: '[email protected],
          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;
    });
}

The email sends, but I'm still getting unsubstituted templates:

enter image description here

The source code for sendgrid-nodejs mail.js seems to say that as long as there is 'substitutions', it will initialize the mailing class with those substitutions but it's not working:

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

How do you properly substitute variables into templates? Am I using the wrong package?

like image 796
Kyle Truong Avatar asked Nov 06 '25 10:11

Kyle Truong


1 Answers

After a bit more digging, I found the answer in the issues section of their github. I was missing 'substitutionWrappers'. To get it working, all I had to do was add 'substitutionWrappers' to the message along with 'substitutions':

const msg = {
    to: '[email protected]'
    from: '[email protected]',
    subject: 'Receipt for Business Expenses',
    template_id: 'da6db3ae-41e4-4e1a-a71b-f5368ab41c9c',
    substitutionWrappers: [':', ''],
    substitutions: {
      firstname: 'Bobba',
      ordernumber: 'WHAAA',
      orderdate: 'today',
      ordertime: 'NOW!',
    },
  };
like image 62
Kyle Truong Avatar answered Nov 08 '25 05:11

Kyle Truong