Sujit Singh Sujit Singh - 16 days ago 6
Javascript Question

How to read HTML (for email body) from another file in NodeJS

I am new to NodeJS.
I started working on a contact us page, which, when submitted, sends out an acknowledgement email with following HTML to user.

<p>Hello Sujit,</p>
<p>Thank you for approaching us.</p>
<p>We have received your request and our executive will get in touch with you soon.</p>
<p>Thank you.</p>


Following is the code to send email:

var mailer = require("nodemailer");

var emailBody = "<HTML above>";

// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport("SMTP",{
service: "#######",
auth: {
user: "#########",
pass: "#######"
}
});

var mail = {
from: "######################",
to: params.email,
subject: "Welcome user.",
text: "",
html: emailBody
}

smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log("Mail error:>>");
console.log(error);
}else{
console.log("Message sent: " + response.message);
}

smtpTransport.close();
});


Currently, using nodemailer, I am sending this email with the HTML body defined in the same file - app.js. It is working fine so far.
But, is there any way I can separate the HTML with variables/placeholders for "name" and place in some other file, so that the body content can be managed directly? Some way by which I can load the body content into the variable
emailBody
.

Thanks.

ABC ABC
Answer

Yes!! Create one folder with name "templates" inside that create text files for particular email. Like welcome.txt. In welcome.txt write code like

<p>Hello #name,</p>
<p>Thank you for approaching us.</p>

Then using fs module you can read that file like fs.readFile([filepath]) and store this value in variable . Like var mailContent = fs.readFile([filepath]). Then using javascript replace function replace #name with actual name . Like mailContent.replace('#name','abcd')