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?
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: 'recipient@example.org',
from: 'sender@example.org',
templateId: 'd-f43daeeaef504760851f727007e0b5d0',
dynamic_template_data: {
subject: 'Testing Templates',
name: 'Some One',
city: 'Denver',
},
};
sgMail.send(msg);