Sending ejs template using nodemailer Sending ejs template using nodemailer express express

Sending ejs template using nodemailer


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: 'testmail@zoho.com',        pass: '123456'    }});ejs.renderFile(__dirname + "/test.ejs", { name: 'Stranger' }, function (err, data) {if (err) {    console.log(err);} else {    var mainOptions = {        from: '"Tester" testmail@zoho.com',        to: "totest@zoho.com",        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);        }    });}});


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: 'testmail@zoho.com',    pass: '123456'  }});const data = await ejs.renderFile(__dirname + "/test.ejs", { name: 'Stranger' });const mainOptions = {  from: '"Tester" testmail@zoho.com',  to: 'totest@zoho.com',  subject: 'Hello, world!',  html: data};transporter.sendMail(mainOptions, (err, info) => {  if (err) {    console.log(err);  } else {    console.log('Message sent: ' + info.response);  }});