Sending HTML template emails using SMTP in NodeJS

In the earlier posts, I had explained how to send emails in CodeIgniter. Now I would like to explain how to send HTML template emails using SMTP in NodeJS.

Sending HTML template emails using SMTP in NodeJS - Anil Labs - a Technical blog of Anil Kumar Panigrahi

Sending HTML template emails using SMTP in NodeJS – Anil Labs – a Technical blog of Anil Kumar Panigrahi

Create HTML file with inline styles, In the earlier posts, I had explained how to use the HTML tags in the page. So prepare the HTML file.

HTML template file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sending HTML template mails using SMTP in NodeJS</title>
<style type="text/css">
    /* -------------------------------------
    GLOBAL
------------------------------------- */
* {
  margin: 0;
  padding: 0;
  font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
  box-sizing: border-box;
  font-size: 14px;
}
body {
  -webkit-font-smoothing: antialiased;
  -webkit-text-size-adjust: none;
  width: 100% !important;
  height: 100%;
  line-height: 1.6;
}
p{text-align:left;}
</style>
<body>
<div>
    <p>Dear ##firstname,</p>
    <p>It is a demo for Sending HTML template mails using SMTP in NodeJS</p>
    <p>Developed by Anil Kumar Panigrahi (Anil Labs Founder)</p>
</div>
</body>
</html>

Now we will go how to include it into NodeJS

Include the node module

nodemailer

In the NodeJS file like

var nodemailer = require('nodemailer');

Include the SMTP details in a config file

module.exports = {
    Service: 'GoDaddy/Gmail/AWS',
    Host: '', //depends on service
    Username: '',
    Password: '',
    Port: '', //Port depends on service type
    From: '', //From Email address
    FromName: '', //From Name
}

In a main file include node module and mail settings

var nodemailer = require('nodemailer');
var mailset = require('../config/mailsettings.js');
var fs = require("fs");
var path = require('path');

Create function to object for emails

function generateTransporter(){
    var transporter = nodemailer.createTransport("SMTP", {
        port: mailset.Port,
        host: mailset.Host,
        secure: true,
        auth: {
            user: mailset.Username,
            pass: mailset.Password
        },
        debug: true
    });
    return transporter;
}

For Gmail SMTP

function generateTransporter(){
    var transporter = nodemailer.createTransport("SMTP", {
        service: "Gmail",
        auth: {
            user: mailset.Username,
            pass: mailset.Password
        }
    });
    return transporter;
}

In function where we use the object to send emails

var filePath = path.join(__dirname, '../templates/email.html');
var transporter = generateTransporter();
var FirstName = "Anil";
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    data = data.toString();
    data = data.replace(/##firstname/g, FirstName);
    var mailOptions = {
        from: mailset.FromName+'<'+mailset.From+'>', // sender address
        to: toemail, // list of receivers
        subject: 'Sending HTML template mails using SMTP in NodeJS', // Subject line
        html: data // html body
    };
    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
                return console.log(error);
            }
        if(error){
                 response = {"Status" : "Failed"};
            }
        else{
                response = {"Status" : "Success"};
            }
                   
        res.json(response);
    });
});

Hope it will be useful. Please let me know if you face issues with it.

Anil Kumar Panigrahi

With more than 10 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ... Contact : [email protected]

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.