Send Mail In NodeJs Using HTML Templates
Posted By : Vivek Joshi | 26-Dec-2017
For sending a mail in nodejs with HTML templates and writting some dynamic contenet into the mail we are using the node nodemailer and email-templates modules for sending an email in the html formate.
for doing this following steps are required
Step1:- install the nodemailer and email-templates module
npm install nodemailer --save
npm install email-templates --save
npm install ejs --save
Step2:- first we have to setup the template engine for express application write the bellow code into the main starting point of express application.
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('view engine', 'ejs');
Step3:- create an template folder for sending different mail body format in HTML.
e.g (create an folder in you application templates-->testMailTemplate)
then create html.ejs ,subject.ejs,text.ejs files int the testMailTemplate for creating body of email.
e.g creating the body of email in file html.ejs
<html>
<head>
</head>
<body>
<div style="margin:0 auto;max-width:600px;">
<p>Hi,{userName}</br>
How are you It's testing mail
</br></br>
Thanks
</div>
</body>
</html>
In html.ejs file {userName} is the dynamic content which will be bing at the time of sending mail to user.
Step 4:- Send mail to user
var require = require('email-templates').EmailTemplate;
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodemailer.createTransport({
host: 'smtpout.secureserver.net', //host of mail service provider
port: 465,
secure: true,
auth: {
user: <sender email id>,
pass: <sender email password>
}
});
function sendMail(){
//create the path of email template folder
var templateDir = path.join(__dirname, "../", 'templates', 'testMailTemplate')
var testMailTemplate = new EmailTemplate(templateDir)
var locals = {
userName: "XYZ" //dynamic data for bind into the template
};
testMailTemplate.render(locals, function (err, temp) {
if (err) {
console.log("error", err);
} else {
transporter.sendMail({
from: <from mailId>,
to: <list of to mail id seperated by comma>,
subject: "test mail",
text: temp.text,
html: temp.html
}, function (error, info) {
if (error) {
console.log(error);
}
console.log('Message sent: ' + info.response);
})
}
})
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vivek Joshi
Vivek is Web App Developer in Java Technology and also working on NodeJS.