1

I have followed the SendGrid docs in order to create dynamic transactional email. But for somehow I could not assign the variables. They always returns empty.

const sgMail = require("@sendgrid/mail")
const SENDGRID_API_KEY = "deleted for safety, no worries i fill the right value here"
sgMail.setSubstitutionWrappers("{{", "}}")
sgMail.setApiKey(SENDGRID_API_KEY)

const msg = {
    to: "deleted for safety, no worries i fill the right value here",
    from: "deleted for safety, no worries i fill the right value here",
    subject: "Hello world",
    text: "Hello plain world!",
    html: "<p>Hello HTML world!</p>",
    templateId: "deleted for safety, no worries i fill the right value here",
    substitutions: {
        name: "Some One",
        city: "Denver",
    },
};
sgMail.send(msg); 

Template:

<html>
<head>
    <title></title>
</head>
<body>
Hello {{name}},
<br /><br/>
I'm glad you are trying out the template feature!
<br><br>
I hope you are having a great day in {{city}} :)
<br /><br/>
</body>
</html>

Result:

Hello,

I'm glad you are trying out the template feature!

I hope you are having a great day in :)

Api keys are correct and the result is the mail I get. Can you guys tell me what I am missing?

3
  • I'm guessing you grabbed this example from here. What I realized in your code is that you have name repeated in the substitutions property of the msg. Not sure if that might be the problem. Commented Aug 12, 2018 at 18:52
  • Yes i took it from there, and no it's just a typo. Thank you for pointing out. I've edited it. Commented Aug 12, 2018 at 19:14
  • It's been already answered over here, go and check it out. Commented Aug 12, 2018 at 19:20

1 Answer 1

1

Install the latest version of @sendgrid/mail package and follow the instructions on following link on official documentation Transactional Templates Use Case

The thing is now you have to use dynamic_template_data instead of substitutions. You also can delete this line

sgMail.setSubstitutionWrappers("{{", "}}")

because starting with v3 API, there's no need to specify the substitution wrappers as it will assume that you're using handlebars.

Here is an example that should work:

 const sgMail = require('@sendgrid/mail');
   sgMail.setApiKey(process.env.SENDGRID_API_KEY);
   const msg = {
     to: '[email protected]',
     from: '[email protected]',
     templateId: 'd-f43daeeaef504760851f727007e0b5d0',
     dynamic_template_data: {
     subject: 'Testing Templates',
        name: 'Some One',
        city: 'Denver',
      },
   };

sgMail.send(msg);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.