An Extended Guide on Sending Emails in Node.JS


Node.JS is a server-side JavaScript engine cherished by web developers and QA analysts worldwide. It has a rich set of modules you can install using the Node Package Manager (NPM) and use to perform almost any task. Specifically, some of them, such as Nodemailer, Emailjs, Imap, Sendmail, etc. will be useful for " target="_blank">Node.JS is a server-side JavaScript engine cherished by web developers and QA analysts worldwide. It has a rich set of modules you can install using the Node Package Manager (NPM) and use to perform almost any task. Specifically, some of them, such as Nodemailer, Emailjs, Imap, Sendmail, etc. will be useful for sending emails through Node.JS.

Before we start, make sure you have:

  • JavaScript (JS) 6.x or later installed on your computer.
  • Installed NPM.
  • An email account, for example, Gmail.
  • A text editor for writing Node.JS code.
  • We also presume that you possess basic knowledge of Node.JS and JavaScript.

Nodemailer Module

When working on the backend for an application or web service, one of the most useful and recurring features is the automatic sending of emails. You can either receive messages from a contact form, send confirmation emails, or perform numerous other things.

However, what is part of the standard repertoire in PHP is absent in the core of Node.JS. Though, there is an easy solution to the mailing problem. With the NPM Nodemailer package you can integrate the functionality for sending emails in Node.JS into your product in a few steps.

Install and Configure Nodemailer

Like most packages for Node.js, Nodemailer is an open-source project maintained on GitHub and licensed under the MIT License. On the occasion of the current installation, we will use a Gmail account, but in the Nodemailer documentation we can find instructions to do it with various services.

The operation is quite simple. First, we need to install the Nodemailer library using NPM:

Example: Install NodeMailer
npm install nodemailer –save

Next, we define a mailCtrl.JS controller that exports the sendEmail() method:

var nodemailer = require('nodemailer'); // email sender function 
    
exports.sendEmail = function(req, res){
    // nodemailer stuff will go here
};

To send an email, we must first define a transporter. We will do it in the following way, replacing the data with those of our Gmail account:

Example: Define Transporter
var transporter = nodemailer.createTransport({
       service: 'Gmail',
       auth: {
           user: '[email protected]',
           pass: 'password'
       }
});

In simple cases, the connection URL to an SMTP server is sufficient as a configuration object. If you omit the second argument, Nodemailer's default values appear.

With the resulting transporter, you can now use the sendMail method to send your emails. You need a configuration object, which you can use to specify the sender, recipient, subject, and message itself. The second argument is a callback function executed after the message has been sent.

Sending emails from Node.js with Nodemailer

Now that we have the transporter, we will define the email itself.

Example: Configure email Options
var mailOptions = {
    from: 'Sender',
    to: '[email protected]',
    subject: 'Subject',
    text: 'Email content'
};

And now we only have to send the email.

Example: Send emails using Transporter
transporter.sendMail(mailOptions, function(error, info){
    if (error){
        console.log(error);
        res.send(500, err.message);
    } else {
        console.log("Email sent");
        res.status(200).jsonp(req.body);
    }
});

After this, our mailCtrl.js file should look like this:

Example: mailCtrl.js
var nodemailer = require('nodemailer');
// email sender function
exports.sendEmail = function(req, res){
    // define the transporter
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: '[email protected]',
            pass: 'password'
        }
    });

    // Define the email
    var mailOptions = {
        from: 'Sender',
        to: '[email protected]',
        subject: 'Subject',
        text: 'Email content'
    };

    // We send the email
    transporter.sendMail(mailOptions, function(error, info){
        if (error) {
            console.log(error);
            res.send(500, err.message);
        } else {
            console.log("Email sent");
            res.status(200).jsonp(req.body);
        }
    });
};

In many cases, however, specifying a character string for configuring the transporter is not sufficient. Alternatively, you can use a configuration object that gives you precise control over how the transporter should behave. For example, you can specify the hostname and port number for the connection.

You can also send emails via Node.JS with an SSL connection. It is better to do it by default to prevent unauthorized persons from reading your messages. Specify the safe option with the value 'true to establish a secure connection.

Alternatives for sending emails in Node.js

The options for sending emails with Node.JS do not end here, so we have a few other popular solutions for you.

Sending emails in Node.js with SMTP

Not so many manipulations are needed now to send email from your server:

Example: Transporter
var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email via Node.js',
  text: 'That was easy!'
};
  
transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Moreover, you can easily address multiple recipients at the same time, as shown below:

Example: Multiple Recipients
var mailOptions = {
  from: '[email protected]',
  to: '[email protected], [email protected]',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
}

To send HTML-formatted text in your email, use the 'html' attribute instead of the 'text' attribute:

Example: HTML-formatted email
var mailOptions = {
   from: '[email protected]',
   to: '[email protected], [email protected]',
   subject: 'Sending Email using Node.js',
   html: '# Welcome

    That was easy!'
 }

Sending emails in Node.js with email API

An email API captures SMTP server traffic from test and development environments and allows you to automate your test flows, as well as analyze content for spam score and email deliverability.

If you want to use a particular email provider, you should check its documentation to set your API key properly. Then follow this way to send an email:

client.sendString('

{{something}}

', { to: ['[email protected]', '[email protected]'], subject: 'Some Subject', preview': 'The first line', something: 'this is what replaces that thing in the template' }, done);

Send emails in Node.js with Mailtrap Email API

Let's consider sending emails via Mailtrap email API. You can create a free account, go to SMTP Settings in the inbox, copy the Node.JS – Nodemailer transporter configuration and use it to replace the transporter in email.js.

Example: Sending emails via Mailtrap
const nodemailer = require("nodemailer");
module.exports.sendEmail = async (event) => {

    let transporter = nodemailer.createTransport({
      host: "smtp.mailtrap.io",
      port: 2525,
      auth: {
        user: "YOUR Mailtrap User ID",
        pass: "YOUR Mailtrap Password"
      }
    });
  
    let info = await transporter.sendMail({
      from: '"Fred Foo" ', 
      to: "[email protected], [email protected]",
      subject: "Hello", 
      text: "Hello world?",
      html: "Hello world?",
    });
  
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'Go Serverless v1.0! Your function executed successfully!',
        data: {
            messageId: info.messageId,
            previewURL: nodemailer.getTestMessageUrl(info)
        },
      },
      null,
      2
    ),
  };
};

Now head over to your Mailtrap inbox. You might see the new message. Go through each tab (HTML, HTML Source, Text, Raw, Spam Analysis, HTML Check, Tech Info) to ensure and confirm that everything is set up correctly, or implement the suggestions to improve your email if needed. Also, check out the responsiveness tabs to ensure compatibility with multiple devices.

Take notice that broken images and browser compatibility could affect your recipient's experience. The only way to ensure your users don't find out about these issues is to test your emails before sending them to the customers.

Conclusion

We have seen how to use the Nodemailer Module, SMTP, and API settings to send emails with Node.JS and Mailtrap and test them. However, we have only shown some of the features of these tools and technologies. We hope this short tutorial will help you to add mailing capabilities to your Node.JS platform.