Sending HTML Emails in NodeJs with Nodemailer

I have created a small NodeJs/Express application to demonstrate in a simple case how to send HTML emails. I have used Nodemailer to send the emails and Email Templates to create and send emails using custom templates.

In my example, I have used Stream Transport for testing.

let transporter = nodemailer.createTransport({
  streamTransport: true,
  newline: 'unix',
  buffer: true
});

But you could simply change the default transport to use SMTP transport for delivering messages in the production environment. For example:

const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  auth: {
    user: 'username',
    pass: 'password'
  }
});

You could also use one of the predefined service, like SendGrid:

const transporter = nodemailer.createTransport({
  service: 'SendGrid',
  auth: {
    user: 'apikey',
    pass: 'SENDGRID_PASSWORD'
  }
});

Now let’s try to send an HTML email via Email Templates using the configured Nodemailer transport.

const email = new template({
  message: {
    from: '[email protected]',
  },
  send: true,
  transport: transporter, // Use defined Nodemailer transport
  views: {
    options: {
      extension: 'ejs' // Use EJS template engine
    }
  }
});

email
.send({
  template: 'example', // Template name
  message: {
    to: req.body.email
  },
  locals: { // Passing variables to template
    name: req.body.name,
  }
})

By default Email Templates use the preview-email package to preview the sent emails.

HTMl Email Preview