Sending E-mails with Node.JS

In post Writing Restful Service Using Node, Express and Mongodb we created a rest api which creates, delete and get employees from database, this time we will send e-mail over Gmail SMTP server using Nodemailer, as follows:

Create a directory and execute npm init, as follows:

$ cd /Users/ArpitAggarwal/
$ mkdir node-js-send-mail
$ cd /node-js-send-mail
$ npm init

Next, install Nodemailer as a dependency and create server.js which is the default entry point for Node.js to send email:

$ cd /Users/ArpitAggarwal/node-js-send-mail
$ npm install --save nodemailer
$ touch server.js

Copy below content in server.js:


var nodemailer = require('nodemailer');

var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'aggarwalarpit.89',
        pass: 'XXXXXX'
    }
};

var transporter = nodemailer.createTransport(smtpConfig);

// setup e-mail data with unicode symbols
var mailOptions = {
    from: '"Arpit Aggarwal 👥" <aggarwalarpit.89@gmail.com>', // sender address
    to: 'aggarwalarpit.89@gmail.com, aggarwalarpit.89@gmail.com', // list of receivers
    subject: 'Hello from Nodemailer ✔', // Subject line
    text: 'Hello Node', // plaintext body
    html: '<b>✌</b>' // html body
};

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

Next, move to directory /Users/ArpitAggarwal/node-js-send-mail start the app following below command:

$ cd /Users/ArpitAggarwal/node-js-send-mail
$ node server.js

Reference: https://github.com/nodemailer/nodemailer

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s