Create a Dynamic Template in SendGrid and Use it with Node.js/Firebase functions.

aditya nandedkar
7 min readJan 16, 2023

Prerequisites

  • Node installed
  • Have a SendGrid Account Setup
  • Basic JavaScript Knowledge
  • Basic NPM knowledge

Part 1: Creating SendGrid Dynamic Template

The topic today uses SendGrid’s dynamic template feature to set an email’s subject and body text. To set this up, select the “Email API” option in the side navigation menu, then choose “Dynamic Templates”.

Dynamic Templates option under Email API option in the side navigation menu

You will see a screen with a prompt to create your first dynamic template. Select the “Create a Dynamic Template” option.

Give your new template a name: “Aditya’s SendGrid Tutorial”. SendGrid will add this template to a list of available templates. Select the template to see the Template ID (make a note of this, as we will need it in the code later on) and click the "Add Version" button.

Screen showing Adding a new dynamic template.

If you already have another template, click on “Create a Dynamic Template”.

Button for creating a new dynamic template.

Give your new template a name: “Aditya’s SendGrid Tutorial”. SendGrid will add this template to a list of available templates. Select the template to see the Template ID and click the "Add Version" button.

Select “Blank Template” on the screen that appears, then choose “Code Editor”. You should now see the editor view. SendGrid’s editor uses HTML to build the email body; however, when we write the Node.js code, we will send the plain text version.

For now, replace the contents of the editor with the following code:

<p>Hi, {{{name}}}</p>
<p>How are you?</p>
<p>Your Card's expiry date is {{{date}}}</p>

You will notice that we have added {{{name}}} and {{{date}}}. SendGrid's template uses Handlebars to dynamically replace values - we will be leveraging this feature when we write the node.js code.

Now select the settings option from the top left — you may optionally give your template version a name, but the “Subject” field is what we want to modify. Set this value to {{{subject}}} to dynamically load the subject value from our code.

{
"name": "Aditya Nandedkar",
"date": "21st January 2023"
}

Remember that JSON requires keys to be wrapped in quotes!

You should now see the preview on the right side of the screen reflect these values in the template. Remember to hit the Save button to save your changes!

Editor and Preview screen showing the dynamic loading of template values

This completes the creation of a dynamic SendGrid Template for emails, we can also use full custom templates and edit them as needed according to brand guidelines or as per individual’s need and also customize them in the design studio provided by SendGrid.

To use the Custom Email Templates, Select “SendGrid Email Designs”, then choose “Code Editor” if we need to directly change the values or we can select “Design Editor” (This is a highly customizable tool provided by SendGrid which allows you to design a template by drag-drop components).

Once we have our template ready we need to have a SendGrid API key, if someone already has a SendGrid Key, they can skip the next part.

Part 2: Generate an API Key in SendGrid

The final step in configuring your SendGrid account is generating an API key for our code.

Click the back arrow at the top left to return to the main SendGrid page. Then select “Settings” and “API keys”. Choose “Create API Key” to generate a new key.

Settings option in the side navigation menu

You may optionally grant “Full Access” to your key, but for the purpose of this tutorial, you will only need “Mail Send” access.

Be sure to give your key a descriptive name so you will remember its purpose if you access this screen again. Once you have your permissions configured, select “Create and View” to generate the key — save this somewhere safe as you will not be able to view it again.

Create an API screen with the Mail Send permission enabled

This completes the SendGrid configuration, Now it is time to write the code to actually send some emails.

Part 3: Integrating SendGrid Email service for Node.js

I’ll skip the Node.js project setup part as it is available on many blogs around the internet.

Using a Twilio SendGrid helper library is the fastest way to deliver your first email.

Install the helper library

To install the Twilio SendGrid helper library, type the following command into the terminal.

npm install --save @sendgrid/mail

The terminal should print something like.

$npm install --save @sendgrid/mail
+ @sendgrid/mail@7.2.1
added 15 packages from 19 contributors and audited 15 packages in 1.625s
found 0 vulnerabilities

How to send an API email\

You’re now ready to write some code. First, create a file in your project directory. Again, you can use index.js because that's the name of the "main" entry point file in the package.json file.

In your index.js file, require the Node.js helper library. The library will handle setting the Host, https://api.sendgrid.com/v3/, for you.

const sgMail = require('@sendgrid/mail')

Next, use the API key you set up earlier. Use helper library's setApiKey() method. The helper library will pass your key to the API in an Authorization header using Bearer token authentication.

sgMail.setApiKey(SENDGRID_API_KEY)

Now you’re ready to set up your "to", "from", "subject", and message body "text". The helper library allows you to store all this data in a single flat JavaScript object. Assign the object to a variable named msg.

Change the “to” value to a valid email address you can access. This is where your message will be delivered. Change the “from” value to the address you verified during the Sender Identity setup.

The "subject" can be any text. The email body can be either plain text or the using template which we have configured in the previous part. The helper library allows you to specify the type of email body by using either the "text" or "HTML" properties.

"text” This text value is overwritten by the template. However, it is still important to use. SendGrid can send emails as plaintext or html - by using the text property instead of the html property, we ensure our template is sent as plaintext. Email providers are more likely to flag HTML messages as spam, so this helps increase our deliverability rate.

"templateId” This is the ID for the dynamic template SendGrid should use in the email.

"dynamicTemplateData” These are the values that correspond with our Handlebars strings we set in the dynamic template earlier.

const msg = {
to: 'test@example.com', // Change to your recipient
from: 'test@example.com', // Change to your verified sender
subject: 'Some Subject',
text: 'and easy to do anywhere, even with Node.js',
html: '',
templateId: 'SENDGRID_TEMPLATE_ID',
dynamicTemplateData: {
name: "Aditya Nandedkar",
date: "10 Jan 2023"
}
}

To send the message, pass the msg object as an argument to the helper library's send() method. You can also add then() and catch() methods to log the response status code and headers or catch and log any errors.

This will send the message to the email specified. Unfortunately, our code will run silently and we will not know if each send was successful or not. Let’s add some error handling.

sgMail
.send(msg)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})

The code block is now complete. To send the message, you can run the index.js file with Node.js.

If you receive a 202 status code printed to the console, your message was sent successfully. Check the inbox of the “to” address, and you should see your message.

Complete code block

const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(SENDGRID_API_KEY)
const msg = {
to: 'test@example.com', // Change to your recipient
from: 'test@example.com', // Change to your verified sender
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '',
templateId: 'SENDGRID_TEMPLATE_ID',
dynamicTemplateData: {
name: "Aditya Nandedkar",
date: "10 Jan 2023"
}
}

sgMail
.send(msg)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})

Similar code can also be used in Firebase Cloud Functions. We can use this technique with any technology/framework provided it has a SendGrid third-party Dependency available.

We can also create multiple versions for a template and change the version from the SendGrid dashboard without changing/deploying the actual code base.

Congratulations, you have successfully sent an email using SendGrid in Node.js. 🙏

Show some love ❤️ if you find it useful !!

Thank You! Keep Coding!

--

--

aditya nandedkar

A passionate Flutter developer learning new things daily !