Sending ejs template using nodemailer
I have updated the answer using ES6 and ES8 features, just in case anyone needs it.
Don't forget to use it in an async function.
const fs = require("fs");
const nodemailer = require("nodemailer");
const ejs = require("ejs");
const transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true,
auth: {
user: '[email protected]',
pass: '123456'
}
});
const data = await ejs.renderFile(__dirname + "/test.ejs", { name: 'Stranger' });
const mainOptions = {
from: '"Tester" [email protected]',
to: '[email protected]',
subject: 'Hello, world!',
html: data
};
transporter.sendMail(mainOptions, (err, info) => {
if (err) {
console.log(err);
} else {
console.log('Message sent: ' + info.response);
}
});
The problem is sendMail
gets executed before the fs.readFile
gets completed.
Actually, the readFile can be replaced with ejs.renderFile
which reads file and renders the HTML string. Please try the below refactored code.
var fs = require("fs");
var nodemailer = require("nodemailer");
var ejs = require("ejs");
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, // use SSL
auth: {
user: '[email protected]',
pass: '123456'
}
});
ejs.renderFile(__dirname + "/test.ejs", { name: 'Stranger' }, function (err, data) {
if (err) {
console.log(err);
} else {
var mainOptions = {
from: '"Tester" [email protected]',
to: "[email protected]",
subject: 'Hello, world',
html: data
};
console.log("html data ======================>", mainOptions.html);
transporter.sendMail(mainOptions, function (err, info) {
if (err) {
console.log(err);
} else {
console.log('Message sent: ' + info.response);
}
});
}
});