I want to pass JSON object to Sendgrid template to dynamically generate email content.
I went through all these documentations but I cannot find these two crucial pieces information.
- https://docs.sendgrid.com/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates
- https://docs.sendgrid.com/for-developers/sending-email/using-handlebars
- https://docs.sendgrid.com/for-developers/sending-email/quickstart-nodejs
- How do I send the dynamic JSON object? Where do I include? inside header? msg object? What is the key name?
- How do I include template id? What is the name of the key?
The closest thing answer I can find is here in this doc, but this still fails to answer
- Where do I include this when using Node.js, not cURL??
- What is the key name for template ID? It says I need to specify template ID but how?
The examples only provide html
and json
but not a way to include JSON.
I'm so confused.Did I miss something in the documentations?
What steps should I take to figure this out by myself without asking for help?
CodePudding user response:
You will need to pass an object to sengrind.send method, and include on it the attrs "dynamic_template_data" and "template_id". Something like:
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const msg = {
to: '[email protected]', // Change to your recipient
from: '[email protected]', // Change to your verified sender
dynamic_template_data: { ... },
template_id: "the_id_of_the_template_you_create_on_sendgrid"
}
sgMail
.send(msg)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
Note: you will need to create a Template on the Sendgrid template builder, and set the keys there. Then you can match keys from your nodejs App. Subject of this Emails are defined on the template that you create on Sendgrid.