Send Mail In Node.Js Using HTML Templates

Hey Everyone,

In this article, we will learn how a sending mail in node.js with HTML templates and write some dynamic content into the mail we are using the node nodemailer modules for sending an email in the HTML format.

There are a variety of template libraries. Some of the popular templates are handlebars, pug/jade, EJS, etc. We will use express.js to handle routing and EJS(Embedded JavaScript Templates) which is a very popular library.

One of the reasons EJS is so popular is because it allows us to write JavaScript code directly inside the template so we can use loops, if conditions, and all things provided by JavaScript. Other template libraries use their own syntax so we can not directly write JavaScript.

Let’s start by setting up our project directory. Create a folder and name it Send Mail Using Dynamic Content. Open the folder with Visual Studio Code. Once inside the VS Code, open the terminal.

Create a package.json file by running:

npm init -y

Once created, Execute the following command to install express, nodemailer, dotenv, body-parser and ejs  dependencies in your node js app:

npm i express nodemailer dotenv body-parser ejs

After installing the above dependencies, create an index.js file, So go to your app root directory and create it.
Now put the below code inside it:

const express = require('express');
const app = express();
var bodyParser = require('body-parser');
require('dotenv').config();
const PORT = 3000;

app.set('view engine', 'ejs');
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
    res.send("Hello");
});
app.use('/', require('./Routes/send-mail'));
app.listen(PORT, console.log(`Listerning server at port ${PORT}`))

Now, Add HTML Template for email templating create a folder, and name it views. Inside this folder create one file mail.ejs and put the below code inside it:

<table width="100%" border="0" align="center" cellpadding="7" cellspacing="0" bgcolor="#e5e5e5"
    style="font-family:Arial;   font-size: 13px; margin:0px auto;">
    <tr>
        <td style="padding:20px">
            <table align="center" border="0" cellpadding="15" cellspacing="0" width="600px"
                style=" border-top:2px solid #00a887;border-bottom:2px solid #00a887;">
                <tbody>
                <tr style="background:#00A551;">
            <td valign="top" width="50%" style="padding:20px;border-bottom:1px solid #eee;font-size:20px;color:#fff; font-weight:bold">Welcome</td>
          </tr>
                    <tr bgcolor="#ffffff">
                        <td style="font-family:arial; font-size:15px; border:1px solid #ffffff; color:#333;">
                            <h3>Hello <%= name %>
                                ,</h3>
                            <p>We're glad to have you on board at <%= company %>.</p>
                            <br>
                            <p><b>Regards,</b><br /><br /><b>Team <%= company %>!!</b></p>
                        </td>
                    </tr>
                    <tr>
              <td style="padding: 16px;" valign="top" align="center" bgcolor="#00A551">
                  <table cellspacing="0" cellpadding="0" border="0" align="center">
                      <tbody>
                          <tr>
                              <td style="font-family: 'Arial', sans-serif; font-size: 13px; ; line-height: 20px; font-weight: normal; color: #ffffff;" valign="top" align="left">
                                  This is an automated message.
                              </td>
                          </tr>
                      </tbody>
                  </table>
              </td>
          </tr>
                </tbody>
            </table>
        </td>
    </tr>
</table>

For sending mail create one folder and name it Routes, inside this folder create one file send-mail.js, and put the below code inside it:

const express = require('express');
const router = express.Router();
const app = express();
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.SENDER_EMAIL,
        pass: process.env.PASSWORD,
    }
});

router.post('/sendmail', function (req, res) {

    app.render('mail.ejs', { name: req.body.name, company: req.body.company }, function (err, html) {
        if (err) {
            console.log('error rendering email template:', err)
            return
        } else {
            var mailOptions = {
                from: process.env.SENDER_EMAIL,
                to: process.env.RECEIVER_EMAIL,
                subject: 'Welcome',
                generateTextFromHtml: true,
                html: html
            };
            transporter.sendMail(mailOptions, function (error, response) {
                if (error) {
                    console.log(error);
                    res.send('Mail Error! Try again')
                } else {
                    console.log(response);

                    res.send("Mail succesfully sent!")
                }
            });
        }
    });
});

module.exports = router;

Now, we have to create an environment (.env) variables setup.

Create an environment (.env) file in the root directory of the project and add the following:

SENDER_EMAIL=ENTER_SENDER_EMAIL
RECEIVER_EMAIL=ENTER_RECEIVER_EMAIL
PASSWORD=ENTER_GMAIL_PASSWORD

Output:

I hope you guys understand how I can do this. If you have any suggestions for improvement or thoughts on better ways please let me know in the comments.

Also check, How to enable auto-attach debug in vs code.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories