Last Updated: February 25, 2016
·
685
· chareesa

You've got mail.. from Node.js!

Nodemailer is a module that makes it easy to send informative emails with Node.js. This can be a highly useful tool for retrieving or sending data from user activity on your site.

Let's look at Nodemailer in its simplest form.. sending an email when your server is run successfully.

First, let's run the installer

npm install nodemailer

Then, let's get a server started:

var http = require('http');

function start(route, handle) {
  function onRequest(request, response) {
    console.log('request received.');
    response.writeHead(200, {"Content-Type":
      "text/plain"});
    response.write('Starting point.');
    response.end();
  }
http.createServer(onRequest).listen(3214);
console.log("Server has started.");
}
exports.start = start;

And in its own file, Nodemailer will have four parts:<br>
Adding the requirements and start()..

var nodemailer = require('nodemailer');
var server = require('./server');
server.start();

Declaring the transporter (the object sending mail)..

var transporter = nodemailer.createTransport({
  service: 'EmailServiceProvider',
  auth: {
      user: 'name1@email.com',
      pass: 'userpassword'
  }
});

Selecting mail options (there are several)..

//setup e-mail data with unicode symbols
  var mailOptions = {
    from: 'Tester ✔ <name1@email.com>',
    to: 'name2@email.com',
    subject: 'Testing test ✔',
    text: 'It works! ✔',  //plaintext body
    html: '<p>It works</p>'//rich text html body
 };

And calling the transporter to send the email.

//send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
  if(error){
    console.log(error);
  }else{
    console.log('Message sent: ' + info.response);
   }
});

THAT'S IT!<br>
Once you've done this.. Nodemailer is ready to go!

It even supports gigabyte attachments by relying on Streams2. There are many optional features that most people won't need, so that's why Nodemailer has a plugin system. You can get just what you need.

If you use an email account with this module that has a 2-step verification process or if access for less secure apps is disabled.. you may need to go into your security settings and make a couple changes. For Gmail, you can go here to do this: https://www.google.com/settings/security.

With Nodemailer, there is so much potential for information gathering, it's quite exciting!

Here's the source of information: https://github.com/andris9/Nodemailer