Home > OS >  How to send JSON object to Sengrid dynamic template using Node.js?
How to send JSON object to Sengrid dynamic template using Node.js?

Time:09-17

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.

  1. How do I send the dynamic JSON object? Where do I include? inside header? msg object? What is the key name?
  2. 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

  1. Where do I include this when using Node.js, not cURL??
  2. 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.

  • Related