2
votes

I'm just trying to set up a trial email for SendGrid, it's the first time I've used it so I'm sure this is simple, but I can't seem to get the placeholder data to replace.

I'm using NodeJS library like this:

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));
});

And in the template there's a text block that I added using the visual editor:

Hello --displayName--

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

from

--companyName--

However when I run the test to send the email, it sends the mail okay, but doesn't substitute the placeholders.

What am I missing here?

3
Check out this question, JohnnyMontana might be right regarding the "dynamic_template_data" tag instead of the "substitutions" tag. - emilal

3 Answers

5
votes

try changing 'substitutions' to 'dynamicTemplateData'. Looks like they changed the name in the new version.

how i figured it out: https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md

3
votes

It is not clear in Sendgrid documentation, but I think it is missing this line:

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

Then remove dashes in substitutions object keys

Look at this link: Sendgrid

So, your code should be:

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

I hope this helps you!

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

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

It seems user given variables don’t work when you have the angle brackets <% ... %> around them, these are reserved for the <%body%> and <%subject%> tags.

So now you can make your template that might look something like this - %displayName%