Node.js Tutorial for Beginners Series (#1) - Send Emails Using Nodemailer Module

in #utopian-io7 years ago (edited)

Introduction

What is node.js?

Node.js is a javascript based server side scripting platform just like php, python or ruby.

Php depends on Apache or nginx web servers for handling http request and response, on the other hand,Node.js has its own http server library allowing us to have more control over the web server.

Definition of Node

Node.js is built on Chrome's JavaScript runtime V8 for developing fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

What is a scalable network application?

An application is said to be scalable when it is efficient and practical when applied to large situations(eg: large input data set, a large number of outputs or users). If the application fails when quantity increases, it is not scalable.

What is an event-driven, non-blocking I/O model?

When you are using a traditional web server like Apache, when a request is received, it processes that request and goes to next request. if that request takes time, the server will wait for it and then moves to the next request. In order to process more requests, the web server uses multiple threads-which is more resource consuming.

In event-driven or non-blocking I/O model the web server accepts the request, then goes back to service next web request(it does not block that I/O operation). When the original request is completed, it comes back in the processing queue and then the results are sent to the browser. This makes it highly efficient and scalable. This is what made nginx webserver very popular. nginx uses a scalable event-driven (asynchronous) architecture. The same technology is used in node.js in a much efficient way.

To Handle 10,000 simultaneous requests node.js uses a few MB of RAM whereas Apache would probably consume hundreds of MB.

Benchmark-
100 concurrent clients
1 megabyte response
node.js-> 822 requests/sec
nginx-> 708 requests/sec
thin-> 85 requests/sec
mongrel-> 4 requests/sec
(bigger is better)

What Will I Learn?

  • Advantages of node.js
  • Basic terminology.
  • Install node.js on windows, mac, and Linux.
  • Write simple programs.
  • Learn about NPM.
  • Installing modules.
  • Node.js express tutorial.
  • Node.js MongoDB tutorial.
  • Node.js MySQL tutorial.
  • Installation of Nodemailer Module.
  • Configuring and Sending email using Nodemailer module using the Gmail SMTP.
  • Installation of Nodemailer Module.
  • Configuring and Sending email using Nodemailer module using the Gmail SMTP.

Requirements

  • Basic knowledge of html
  • Basic knowledge of javascript

Difficulty

  • Basic

Advantages of node.js

  • Node.js uses javascript and it is easy to learn.
  • Node.js runs on v8 Engine (a javascript interpreter: chrome uses it) which is very fast.
  • We can build highly scalable web applications using node.js
  • We can develop chat based applications, online games, API and many more.
  • Supports interaction with all major databases.
  • Node.js has 1000's of third-party free modules.
Companies depending on node.js

eBay, Microsoft, Yahoo!, StrongLoop, OmniTI, Storify, local response, nodejitsu, Linkedin, Iris Couch, backbeam, recruitics, Transloadit, Uber, Voxer,when-to-manage, Jaleoo, Cloud9 IDE, NODE the FIRM etc..

Basic terminology

Asynchronous- Asynchronous means an event which is happening independently of other events. The main advantage of the asynchronous approach is scalability.

Npm- Stands for node package manager. This will help us install the latest modules directly from the servers instead of checking for the latest version, downloading and copying to the appropriate directory. It also has other uses.

Express- Express is a highly recommended web application framework for node.js. It takes care of the low-level services for us.

Module- A module is an independent, reusable piece of code. you can download them and use them directly in your project. ex: express, http, https etc are some of the modules for node.js.

REPL-Read-Eval-Print-Loop provides a way to interact with javascript it can be used for debugging, testing. To try repl go to terminal(cmd prompt) and type node and try ex: console.log("learn nodejs");

Mongoose- Mongoose is a MongoDB object modeling tool for node.js. It becomes easy to interact with MongoDB database server using Mongoose module.

Db-mysql- It is a node.js module to interact with MySQL database.

Installing Node.js

Installation on windows
  • goto->nodejs.org->click on Install button->that will download a node windows installer.
  • install it just like any other application.
  • restart the computer.
  • open cmd prompt->type in node --version->it will show the node.js version number.
  • you can also check the npm version using npm --version command.
Installation on Mac
  • installing node.js on mac as same as for windows.
  • you can also use brew to install node.js->brew install node
  • or use macports->port install nodejs
Installation on linux

Note
If you have any problems during Linux installation please make sure you have python and OpenSSL installed.

Try this: node.js example 1

  • Create a file named nodeexample1.js
  • Add the following code in it and save.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('First node.js example');
}).listen(8123);
console.log('Server running at http://localhost:8123/');

->goto->cmd prompt->enter the directory where u saved the file->type in node nodeexample.js(u ll get: server running at 127.0.0.1:8123).

->then open browser and type->http://localhost:8124

->output-> First node.js example

->use ctrl+c to stop the server.

Explanation of example1

line1->when ever we are using any modules(built-in or external), we have to include them first.

line2->http.createServer will return a new web server object. we have to create a server object to use http server.

line3->sends a response to the browser. You can also use response.write() method. these must be used only before response.end() method.

line4->listens to the port. You can send an optional parameter of 'localhost'.

line5->console.log() will output to the console and not the browser window.

Note- Whenever you modify the file, don't forget to restart the server ie., stop the server using ctrl+c and run the file again.

Try this: node.js example 2

  • We will have a look at how to load static files
  • create a file named nodejsexample2.js and copy the following code in it.
var http = require('http');
var fs = require('fs');
http.createServer(function (request, response) {
fs.readFile('index.html','utf8', function (err, data) {
if (err){
response.write('unable to load the requested file');}
else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
}
response.end();
});
}).listen(8123);
console.log('Server running at http://localhost:8123/');

->now run the file to start the server.

->goto->http://localhost:8123.

->the output will be the contents of the file.

Explanation

line2-> We have included filesystem module. Using this module we will be able to access the file system.This is builtin module no need to download it.

line4-> readFile() function is used to read the files from the disk. function(err, data) is the callback function and it is mandatory.what happens here is node.js will not wait for the response and will carry on with the execution and when the response is ready it will be outputted.

line5-> If there is an error reading the file there will be one response. If everything ok then else part is executed. here 'data' stores the contents of your file we can change the name, and make sure that index.html exists in your current directory.

Send Emails Using Nodemailer Module

What is the Importance of E-mail?

Email is the electronic version of the traditional mail. Email is fast, secure, reliable and widely used by millions of people in today’s world.

  • E-mail is used for the variety of different situations such as newsletters, contact forms, formal Communication, informal communication and many more. E-mail helps businesses to expand their customer base by sending new offers, newsletters and customer support communication.

  • Businesses use newsletters to update their customer about their new products and services, thereby driving web traffic to their site.

Ways in Which We Can Send Email or Protocols Used To Send Email

There are many different protocols in which we can send emails the most widely used protocols are IMAP, POP3, SMTP, HTTP and many more like Amazon SES. Keep a note of the port which is useful for sending and receiving emails through our code.

  • SMTP: Stands for Simple Mail Transfer Protocol is most widely used a protocol to send and receive emails messages. It uses TCP port 25 for sending and receiving emails. SMTP connections secured by SSL are known as SMTPS which uses TCP port 465.
  • POP3: Stands for Post Office Protocol is used for receiving an email from a server. It is also widely used Protocol to receive email. It listens on well-known TCP port 110. IMAP over SSL (IMAPS) listen on port 995
  • IMAP: Stands for Internet Message Access Protocol is used for receiving an email from a server. It listens on well-known TCP port 143. IMAP over SSL (IMAPS) listen on port 993
  • HTTP: HTTP protocol is generally not used for email communication, but sometimes it can be used to access email; known as web-based email. Hotmail is one of the best examples which use this protocol.
Benefits of Using Nodemailer Module for Node.js
  • We can send Attachments (including attachment streaming for sending larger files.)
  • We can even embed images in HTML.
  • Support for SSL/STARTTLS for secure e-mail delivery.
  • Supports a variety of transport methods – SMTP, send email and Amazon SES.
  • SMTP Connection pool and connection reuse for rapid delivery.
  • Preconfigured services for using SMTP with Gmail, Hotmail etc.
  • Use objects as header values for SendGrid SMTP API.
  • It also supports XOAUTH2 authentication and token generation support – useful with Gmail.
  • DKIM signing.
Steps to Create a Simple Email Application
  • Install node.js
  • Execute the following commands in order.
npm install express –g
npm install jade –g
npm install nodemailer –g
express email (project name)
cd email
npm link express
npm link jade
npm link nodemailer
node app.js //to run the app

And go to your favorite browser (any browser) and type “localhost:3000″ in the address bar and press enter. If you get the “welcome to express” page you have successfully created an app in node.js using express.

Let’s Set Up the Email Script, Follow the Steps Given Below

Step 1

Open index.jade file inside /view folder and replace it with following code.

extends layout

block content
form(action='/contact', name='contactus', id='contactus', method='post')
p
label(for='name') Name:
br
input(name='name', type='text', value='', id='name')
p
label(for='email') Email:
br
input(name='email', type='text', value='', id='email')
p
label(for='message') Message:
br
textarea(name='message', cols='40', rows='10', id='message')
p
input(name='submit', type='submit', value='Send', id='submit')
  • “Extends layout” simply means use the default header stated in layout.jade file like include in php.
  • We have a form with action as /contact and the method used to send form data is post.
  • You can learn more about jade template engine at jade-lang.com/
Step 2

Open app.js file inside the email folder and replace it with following code.

/**
Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//include the nodemailer module
var nodemailer = require('nodemailer');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/contact', function (req, res) {
var mailOpts, smtpConfig;
smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "[email protected]",
pass: "yourpasswordhere"
}
});
//construct the email sending module
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: ' yourGmailidGoesHere @gmail.com',
//replace it with id you want to send multiple must be separated by ,(comma)
subject: 'contact form',
text: req.body.message
};
//send Email
smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email sent successfully
else {
res.end("Email sent successfully");
}
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

Explanation of the Code

Let’s Examine the Following Code
//include the nodemailer module
var nodemailer = require('nodemailer');

This code simply loads nodemailer module and this is the first step.

Let’s Examine the Following Code (Email Module)

app.post('/contact', function (req, res) {
var mailOpts, smtpConfig;
smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: " yourGmailidGoesHere @gmail.com",
pass: "yourpasswordgoeshere"
}
});
//construct the email sending module
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: '[email protected]',
//replace it with id you want to send multiple must be separated by , (Comma)
subject: 'contact form',
text: req.body.message
};
//send Email
smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email send sucessfully
else {
res.end("Email send sucessfully");
}
});
});

This is our email sending module where “var mailOpts, smtpConfig” are the two objects which store our SMTP configuration and mail sending options.

Let’s Examine the Following Code

smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "[email protected]",
pass: "yourpasswordgoeshere"
}
});

Here we store the Gmail email id and password which will be passed to every sent mail. When nodemailer calls Gmail, it passes this information and Gmail will authenticate and then only sends an email. So it is important that we should have an active Gmail email id and password for this module to work.

Let’s Examine the Following Code

mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: '[email protected]', //replace it with id you want to send multiple must be separated by ,
subject: 'contact form',
text: req.body.message
};

Here we store from, to, subject and the message that need to be send. We can send email to multiple ids by simply separating email address with comma.

Let’s Examine the Following Code

smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email send sucessfully
else {
res.end("Email send sucessfully");
}
});

This is the most important code. Here we send the actual email and pass all the required email header information such as to, from, message using the mailOpts object with the emailid and password used to send this email.

Node.js Mail Tutorial Conclusion

We have used the free Gmail SMTP and nodemailer Email module to send emails in node.js since Gmail is a widely used email service provider. We can use other email providers such as Yahoo, Zoho etc. nodemailer also supports XOAUTH2 authentication protocol. To use this you need to obtain a Client ID and a Client Secret from Google API Console.

There are other email sending modules such as simplesmtp, IMAP, SMTP-protocol, etc… But nodemailer is widely used, supports most of the features, easy to implement and support windows.

I hope this tutorial added some value to you. I am more than happy and found it all fun putting this together just for you. I wish to do more and I will.

Thanks for your time.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for your contribution, yet it cannot be approved because it does not follow the Utopian Rules.
Portions of your description were actually taken from other sources without referencing them, this is considered plagiarism. (such as description of scalability: https://en.wikipedia.org/wiki/Scalability)
You have promised many things that were NOT delivered in the tutorial, such as mongodb and mysql tutorial.
Portions of your code were actually taken also from other sources as they are. Here is one example reference: https://modernweb.com/express-js-fundamentals/

You can contact us on Discord.
[utopian-moderator]

Hey @mcfarhat, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Congratulations @graciousrecipe! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of comments
You got a First Reply

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Coin Marketplace

STEEM 0.22
TRX 0.27
JST 0.041
BTC 103494.73
ETH 3835.74
SBD 3.33