Did you know you can send and receive emails using node.js? If not, I have a simple tutorial planned just for you. Having basic knowledge of node.js is enough to understand this article.





Before we get into coding, let us understand these simple terms: SMTP & IMAP.

SMTP, Simple mail transfer protocol, is the protocol used to send emails from one server to another and is used to send emails by most mailing clients including Gmail.

Now, to access/retrieve these received messages, we use IMAP or POP3. In general, IMAP is preferred.

Why IMAP?

POP3 (Post office protocol v3) receives emails, and deletes them from the server, while IMAP(Internet message access protocol) receives without deleting, which makes it possible to access emails from the same account through different devices and places.

Now that we understand what SMTP and IMAP basically do. Let’s get into coding.



Sending emails

Required modules:

1.Nodemailer: Nodemailer is the module used for sending emails.

Installation:

npm install nodemailer --save



2. xoauth2 : This module is used for generating tokens, sending and receiving emails.

npm install xoauth2



Program for sending email

Step 1: Including necessary modules

const nodemailer = require(‘nodemailer’); const xoauth2 = require(‘xoauth2’);



Step 2: Creating a transporter method

let transporter = nodemailer.createTransport({ service: ‘gmail’, host: ‘smtp.gmail.com’, secure: ‘true’, port: ‘465’, auth: { type: ‘OAuth2’, //Authentication type user: ‘your_email@service.com’, //For example, xyz@gmail.com clientId: ‘Your_ClientID’, clientSecret: ‘Client_Secret’, refreshToken: ‘Refresh_Token’ } });







For learning how to know your client id, client secret and refresh token, refer to the section “Getting credentials for OAuth2”









Step 3: Defining mails options such as to, from, content etc

let mailOptions = { from: ‘your_email@service.com’, to: ‘receiver_email@service.com’, subject: ‘This is subject’, text: ‘This is email content’};

You can add more fields in step 3. To know which field can be added, refer here: http://nodemailer.com/message/









Step 4: Finally, sendMail method, e = error message, otherwise sent log will be displayed

transporter.sendMail(mailOptions, function(e, r) { if (e) { console.log(e);} else { console.log(r); } transporter.close(); });

See! How easy it was! If you want to learn more about nodemailer module we used here, visit their official website.



Getting credentials for OAuth2

In this section, you’ll learn how to get your own Client id, Client secret key and refresh token.

Getting Client id and secret through Google console API





Getting Refresh token through OAuth 2.0 playground





If you don't want to follow the above steps, you can simply replace Client id, client secret and refresh token fields by password and enable less secure apps in Gmail to make it work!

We’ll use just password in Receiving script to illustrate this.

Receiving emails

Modules required

1.node-imap : We’ll use this module for receiving raw emails.

Installation: npm install imap

2. filesystem* (for saving the raw email received into txt files)





Program

Step 1: Include required modules

var Imap = require(‘imap’), inspect = require(‘util’).inspect; var fs = require(‘fs’), fileStream;

Step 2: Declaring new imap object

var imap = new Imap({ user: ‘your_email@service.com’, password: ‘yourPassword’, host: ‘imap.gmail.com’, port: 993, tls: true });

Remember, using just password for authentication will only work if you have less secured apps enabled, as mentioned in previous section.





Step 3: Driver program to receive emails.

This pretty much contains receiving emails, deciding which parts of email to receive, and what to display on the console after execution of the program.

function openInbox(cb) { imap.openBox(‘INBOX’, true, cb); } imap.once(‘ready’, function() { openInbox(function(err, box) { if (err) throw err; imap.search([ ‘UNSEEN’, [‘SINCE’, ‘June 15, 2018’] ], function(err, results) { if (err) throw err; var f = imap.fetch(results, { bodies: ‘’ }); f.on(‘message’, function(msg, seqno) { console.log(‘Message #%d’, seqno); var prefix = ‘(#’ + seqno + ‘) ‘; msg.on(‘body’, function(stream, info) { console.log(prefix + ‘Body’); stream.pipe(fs.createWriteStream(‘msg-’ + seqno + ‘-body.txt’)); }); msg.once(‘attributes’, function(attrs) { console.log(prefix + ‘Attributes: %s’, inspect(attrs, false, 8)); }); msg.once(‘end’, function() { console.log(prefix + ‘Finished’); }); }); f.once(‘error’, function(err) { console.log(‘Fetch error: ‘ + err); }); f.once(‘end’, function() { console.log(‘Done fetching all messages!’); imap.end();}); }); }); }); imap.once(‘error’, function(err) { console.log(err); }); imap.once(‘end’, function() { console.log(‘Connection ended’); }); imap.connect();





From the above program you will receive raw, unread mails from the date you selected, each saved in separate ‘.txt’ files.

You can play around more with node-imap and change this program according to your requirements.

You can also make config.json file instead of filling in credentials directly. Also, I’d suggest you learn both methods, but go with the password one while you’re building any emailing application. Even the most popular email clients are using this method.

To check out the full code used in this blog, visit: https://github.com/accakks/Sending-and-Receiving-Emails-using-node.j



