Reputation: 767
I want to send multiple mails by using nodejs. Currently I am using the html code inside the Nodejs script of Route. But when html is going large the Nodejs file also going huge and it is not maintainability.
So how can I use html files externally ?
I am using nodemailer
code externally. Like that I also want to use html
file externally (/api/htmls/registerEmail.html
). But the html
file also using body data also (req.body.fname
)
mailSender.js (/api/routes/r_msg/)
var nodemailer = require('nodemailer');
function sendMail(to, msg, subject)
{
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true,
auth: {
user: '[email protected]',
pass: 'password'
}
});
var mailOptions = {
from: '[email protected]',
to:to,
subject: subject,
html: msg,
};
transporter.sendMail(mailOptions, function(error, info)
{
if (error)
{
console.log(error);
}
})
}
module.exports.sendMail = sendMail;
register.js (/api/routes/)
const express = require('express');
const router = express.Router();
const app = express();
const sendMail = require("../api/routes/r_msg");
router.post("/register/new", (req, res) =>
{
const newStudent = new Student(
{
fname: req.body.fname,
lname: req.body.lname,
contact_no: req.body.lname,
email : req.body.email
});
newStudent.save()
.then(student =>
{
if (student)
{
//This line want to change
var html = `<html> <body> Hello ` + req.body.fname + `Welcome </body> </html>`;
sendMail.sendMail(req.body.email, html, 'Success');
res.status(200).send(setting.status("Success")
console.log('Email sent: ' + info.response);
}
});
}
Upvotes: 1
Views: 221
Reputation: 251
As mentioned in the comment, you can solve it with ejs.
Add this to your register.js:
const ejs = require('ejs');
const promisify = require('util').promisify;
const renderFile = promisify(ejs.renderFile);
// inside route handler:
renderFile(__dirname + "/api/htmls/registerEmail.html", {fname: req.body.fname})
.then(html => {
sendMail.sendMail(req.body.email, html, 'Success');
})
.catch(error => {
// handle error
})
Email template registerEmail.html
<html> <body> Hello <%= fname %> Welcome </body> </html>
Upvotes: 1