How to Send Email with Templates using Nodemailer and Gmail

Using templates in Node is a great way to streamline the email-sending process. The handlebars package in Node makes it simple to insert dynamic values into HTML templates and allows for great separation of concerns when constructing your Node application. Sending emails to your users becomes critical in large scales applications and using dynamic templates will be needed for this.

Step 1-) npm install the following packages

npm install nodemailer express express-handlebars

Step 2-) Create a template file of the html you would like to send

I used the following template saved in the root directory of my application

<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .header h1 {
            color: #333;
            font-size: 24px;
            margin: 0;
        }

        .content {
            margin-bottom: 30px;
        }

        .content p {
            margin: 0 0 10px;
            line-height: 1.5;
        }

        .footer {
            text-align: center;
        }

        .footer p {
            color: #999;
            font-size: 14px;
            margin: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Greetings, {{username}}!</h1>
        </div>
        <div class="content">
            <p>Thank you for being a valued member of our community.</p>
            <p>We appreciate your continued support and would like to offer you a special discount on your next purchase.</p>
            <p>Simply use the code <strong>WELCOME10</strong> at checkout to enjoy a 10% discount.</p>
            <p>We hope you enjoy your shopping experience with us.</p>
        </div>
        <div class="footer">
            <p>Best regards,</p>
            <p>The Team</p>
        </div>
    </div>
</body>
</html>

You can customize the HTML as you like, I named the file email_template.html

The only dynamic value we have in the template is the username as you can see, so in theory, we can send this to any user dynamically, which is nice.

Step 3-) Run the following code

const express = require('express');
const nodemailer = require('nodemailer');
const handlebars = require('handlebars');
const fs = require('fs');

const transporter = nodemailer.createTransport({
  host: 'smtp.gmail.email',
  secure: false,
  service: 'gmail',
  auth: {
    user: '<email>',
    pass: '<app password>',
  },
});

const app = express();
const port = 3005;

app.get('/', async (_, res) => {
  const source = fs.readFileSync('email_template.html', 'utf-8').toString();
  const template = handlebars.compile(source);
  const replacements = {
    username: 'Shilleh',
  };
  const htmlToSend = template(replacements);

  const info = await transporter.sendMail({
    from: '<some email>',
    to: '<some email>',
    subject: 'Hello from node',
    text: 'Hello world?', // dont really need this but it is recommended to have a text property as well
    html: htmlToSend
  });

  console.log('Message sent: %s', info.response);
  res.send('Email Sent!');
});

app.listen(port, () => {
  console.log(`App is listening on port ${port} !`);
});

Make sure to replace the information accordingly. You need an app password from your Gmail account. Other than that, we use the handlebars library to simply replace the username in the compiled template, very easy to do.

In this simple example, I run a very basic express server and hit the base URL, afterward receiving an email with the correct template. You can place the function accordingly based on your application’s needs.

Conclusion:

Do not forget to like, comment, and subscribe to the channel. Hope you got the template working in your Node app, if you have any questions let me know, thanks for your time.

Create a free account to access full content.

All access to code and resources on ShillehTek.

Signup Now

Already a member? Sign In

Explore More on Our Blog

Controlling an LED with a Snap Using the KY-037 Sound Sensor and Raspberry Pi

Controlling an LED with a Snap Using the KY-037 Sound Sensor and Raspberry Pi

Discover how to set up, code, and activate the LED based on detected sound with the Raspberry Pi...

Getting Started with the KY-037 Sound Sensor and Raspberry Pi: Detecting Sound Using Python

Getting Started with the KY-037 Sound Sensor and Raspberry Pi: Detecting Sound Using Python

In this tutorial, I’ll guide you through setting up the KY-037 sound sensor with a Raspberry Pi using...

How to Post to Reddit Using Python

How to Post to Reddit Using Python

Post to reddit automatically using a Python script.

How to Create a Time-Lapse Video with a Raspberry Pi Camera

How to Create a Time-Lapse Video with a Raspberry Pi Camera

Learn how to make a timelapse with your Raspberry Pi in Python.

How to Integrate the MPU6050 with the STM32 Blue Pill

How to Integrate the MPU6050 with the STM32 Blue Pill

Learn how to measure acceleration with the STM32 and the MPU6050 in the Arduino IDE.

Getting Started with STM32 Blue Pill in Arduino IDE Using a USB to TTL Converter — Write Your First Program

Getting Started with STM32 Blue Pill in Arduino IDE Using a USB to TTL Converter — Write Your First Program

This comprehensive tutorial will guide you through the process of setting up and programming the STM32 Blue Pill...

Automate Task Scheduling in AWS with Lambda, Step Functions, and CloudWatch

Automate Task Scheduling in AWS with Lambda, Step Functions, and CloudWatch

In this tutorial, I'll show you how to automatically schedule tasks in AWS at regular intervals using AWS...

Implementing Google reCAPTCHA in a Simple React and Node.js App

Implementing Google reCAPTCHA in a Simple React and Node.js App

Learn how to protect your React applications from bots and spam with Google reCAPTCHA integration! This step-by-step tutorial...

AWS Lambda Tutorial: Using Selenium with Chromedriver in Python

AWS Lambda Tutorial: Using Selenium with Chromedriver in Python

In this tutorial, I will guide you through the process of running Selenium with ChromeDriver inside an AWS...

How to Connect MLX90614 Infrared Thermometer to Raspberry Pi Pico W: MicroPython Tutorial!

How to Connect MLX90614 Infrared Thermometer to Raspberry Pi Pico W: MicroPython Tutorial!

Learn how to use the MLX90614 with the Raspberry Pi Pico W and get infrared values in MicroPython.

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.