NodeJS: Send HTML email using EJS and Sendmail

The simplest solution for sending an email with Node would be to use Sendmail. If you want to send an HTML email, use handlebar or ejs for handling the template (I am using ejs here).

We are using a package named node-sendmail (https://www.npmjs.com/package/sendmail) for this purpose.

Sendmail + ejs (or handlebar) = easiest way to send mail in node

Here is how to do it:

  • Install Sendmail: (also install Sendmail in your system)
npm install sendmail —save
  • Install ejs:
npm install ejs —save
  • Now use the following code for sending an email: (check the documentation for Sendmail and ejs package)

For text email:

// index.js

// Import required package
const sendmail = require(‘sendmail’)();

sendmail({
  from: ‘no-reply@example.com’,
  to: ‘test@example.com’,         // multiple email addresses can be set as comma-separated
  subject: ‘Test sendmail with note’,
  html: str,
}, function (err, reply) {
  console.log(err && err.stack);
  console.log(reply);
});


For HTML email:

// index.js

// Import required package
const sendmail = require('sendmail')();

const ejs = require('ejs');

// Data to send in the template
let data = {
  title: 'some title here',
  body: 'some long text for the body here',
  total: 1908.50
};

// get html template and set data in the template
ejs.renderFile('order.mail.ejs', data, {}, function(err, str) {
  // str has the html content with the replaced values from ‘data’
  if(!err) {
    sendmail({
      from: ‘no-reply@example.com’,
      to: ‘test@example.com’,         // multiple email addresses can be set as comma-separated
      subject: ‘Test sendmail with note’,
      html: str,
    }, function (err, reply) {
      console.log(err && err.stack);
      console.log(reply);
    });
}

});

Here is a sample HTML template for email. (This is minimal HTML for testing. Your actual HTML template for email will certainly be different):

<!--- order.mail.ejs -->

<div>
  <h1><%=title %><h1>
  <div><%= body %></div>
  <div><%= total %></div>
</div>

More Info

  • If you have Sendmail installed, then you can also test it from your local machine. (Though Gmail and few other services can cause an issue with the emails sent from the local machine, check the log in the console).
  • You can also use nodemailer(https://nodemailer.com) if you want. Nodemailer is a popular package for sending an email. We will discuss nodemailer in some other article.
  • For more information on the Sendmail package, follow: https://www.npmjs.com/package/sendmail
  • For more information on the ejs package, follow: https://ejs.co/

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.