Send Emails Easily with Node.js

Send Emails Easily with Node.js

Javascript was never intended to be run outside the browser. But the arrival of Node.js changed the game and allowed JavaScript to be run anywhere the Node.js runtime is supported. As a result, the javascript ecosystem exploded with new libraries and packages, that take advantage of Node.js to provide functionalities that were never possible due to the limitations of the browser. One of those packages is Nodemailer.

Nodemailer is a module for Node js to send emails. Lets try sending an email with JavaScript!

First we should install the Nodemailer package using npm:

npm install nodemailer --save

Once installed, we will create a new script file called email.js. We should first require the package we installed using:

const nodemailer = require('nodemailer');

Next we should configure the sender options. To do so, we place all settings into an object:

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'example@gmail.com',
    pass: 'password'
  }
});

Now we set the recipients settings:

var mailOptions = {
  from: 'example@gmail.com',
  to: 'example1@gmail.com, example2@gmail.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy! '
};

To actually send the email, we use the sendMail method provided by Nodemailer:

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

And that's about it !

This is all we need to start sending emails using Node.js.