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

How to Use ADS1115 with the Raspberry Pi (Part 1)

How to Use ADS1115 with the Raspberry Pi (Part 1)

Discover how to expand your Raspberry Pi projects by integrating the ADS1115 ADC for precise analog signal reading....

How to Install Pip Packages in AWS Lambda Using Docker and ECR

How to Install Pip Packages in AWS Lambda Using Docker and ECR

Learn how to streamline AWS Lambda deployments by using Docker and Amazon Elastic Container Registry (ECR) to package...

Create Tabular Product Descriptions on Your Shopify Store

Create Tabular Product Descriptions on Your Shopify Store

Enhance your Shopify store's product pages with our comprehensive guide on implementing tabular descriptions. Learn how to add a...

SSH Into Raspberry Pi with Tailscale VPN

SSH Into Raspberry Pi with Tailscale VPN

Effortlessly access and manage your Raspberry Pi from anywhere using Tailscale's secure mesh VPN.

Send Email with Lua and the ESP32

Send Email with Lua and the ESP32

In this tutorial, we delve into sending emails with the ESP32-S3 using Lua, focusing on the Xedge IDE's built-in SMTP...

How to Code with Lua on ESP32 with XEdge32

How to Code with Lua on ESP32 with XEdge32

Learn how to set up Xedge32 and start coding on the ESP32-S3 with Lua programming!

Stream Audio From Raspberry Pi to Local Computer

Stream Audio From Raspberry Pi to Local Computer

Discover the simplicity of streaming live audio directly from a USB microphone connected to your Raspberry Pi to...

SSH Raspberry Pi via Cell Phone

SSH Raspberry Pi via Cell Phone

This beginner-friendly guide will walk you through remotely controlling your Raspberry Pi using SSH through your cell phone.

Remotely Control Raspberry Pi via SSH from External Network

Remotely Control Raspberry Pi via SSH from External Network

Learn how to SSH into your Raspberry Pi from any network. This is critical in IoT since you can control...

Stream Video from Raspberry Pi Camera to YouTube Live

Stream Video from Raspberry Pi Camera to YouTube Live

Learn how to stream to YouTube from a Raspberry Pi Camera.

Back to blog

Leave a comment

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