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

Simple Guide: Build a Reverse Geolocator with Raspberry Pi Pico W and GPS Module

Simple Guide: Build a Reverse Geolocator with Raspberry Pi Pico W and GPS Module

Back to blog

Leave a comment

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