Send an Email Using Nodemailer in NodeJS and Express
Sending email notification is basic need of any web application. Whether it is used for Sending marketing emails or support email for ECommerce site. We have earlier see how to send an email using shiftMailer in Symfony framework. In this tutorial we will see how to send email in NodeJs using Nodemailer (Official Site). NodeJS is JavaScript framework and it have too many packages which allow you sending emails from your node application.
Send Email using Nodemailer in NodeJS and ExpressJS
We are going to use nodemailer
package to send emails. Nodemailer is single module with zero dependencies sponsored by MoonMail. MoonMail is well-known email marketing software, it also offers free membership with limited functions which is best in the industry. It supports Unicode support, Windows support, HTML content as well as plain text, Embedded image attachment for HTML content, OAuth2 authentication, Proxies for SMTP connections and more features.
- express
- nodemailer
1
2
3
|
app.js
package.json/
node_modules
|
The first steps of development is to install packages. Install all required packages using npm
by executing below command:
1
|
$ npm install <package name> --save
|
Read more about how to install package in node.
Create a RESTFul API Using Node.JS, Express.JS and MongoDB
How to Create Database in MongoDB
After installation of all the packages our package.json
will look like:
1
2
3
4
5
6
7
8
9
|
{
"name": "Demo App",
"version": "1.0.",
"private": true,
"dependencies": {
"express": "^4.15.3",
"nodemailer": "^4.0.1"
}
}
|
Setup express app and set Default port, Body parser to parse parameters. Finally create a server which listen specific port from your system. Make sure that the port you are using is not already used by other application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
var http = require('http'),
express = require('express'),
nodemailer = require('nodemailer'),
parser = require('body-parser'),
util = require('util'),
validator = require('express-validator');
// Setup App
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.use(validator());
// Create NodeJs Server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
|
Our App is up to date, now set transporter configuration for sending email functionality.
Function nodemailer.createTransport()
will create new transport that allows us to send email to single or multiple recipient.
1
2
3
4
5
6
7
8
9
10
|
// Email transporter configuration
var transporter = nodemailer.createTransport({
host: '<host>', //smtp.gmail.com
port: <port>, // secure:true for port 465, secure:false for port 587
secure: true,
auth: {
user: '<email address>',
pass: '<password>'
}
});
|
Update connection information such as host (SMTP host), Port, Auth, Secure (SSL secure or not) in above code.
Create route which allows POST
HTTP method with three parameters such as email, subject and message.
Input Parameters
- subject
- message
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// http://localhost:8080/email/send
app.post('/email/send', function(request, response){
var body = request.body;
// Set email configuration such as Fron email, To email, Subject, HTML body.
var params = {
to: body.email,
subject: body.subject,
html: body.message
};
transporter.sendMail(params, (mailError, mailReponse) => {
if (mailError) {
var arrResponse = {'status':'failure', 'error': mailError};
} else {
var arrResponse = {'status':'success', 'data': mailReponse.accepted};
}
response.status(200).send(JSON.stringify(arrResponse));
});
});
|
You can send email to multiple recipient by adding coma separated email address in to
. Fucntion transporter.sendMail()
sends an email to specified email addresses and returns status code in response for each recipient.
User will pass To email, subject and message parameters from front end and pass them into POST
request.
In this part, we will validate the user inputs. We will express-validator module to validate user inputs.
1
2
3
4
5
6
7
8
9
10
11
|
// Email address is not empty
request.checkBody('email', 'Please enter email address').notEmpty();
// Email address is valid email
request.checkBody('email', 'Please enter valid email address').isEmail();
// Subject is not empty
request.checkBody('subject', 'Please enter subject').notEmpty();
// Subject is not empty
request.checkBody('message', 'Please enter messaage').notEmpty();
|
Apply input validations in route. Copy following and update route. request.getValidationResult().then()
function validates if input parameters validated or not. If any input validation error found than it will return Error message, input field name and status as failure into response.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
// Route
app.post('/email/send', function(request, response){
var body = request.body;
request.checkBody('email', 'Please enter email address').notEmpty();
request.checkBody('email', 'Please enter valid email address').isEmail();
request.checkBody('subject', 'Please enter subject').notEmpty();
request.checkBody('message', 'Please enter messaage').notEmpty();
request.getValidationResult().then(function(result) {
if (!result.isEmpty()) {
var arrResponse = {'status':'error', 'data':util.inspect(result.array())}
response.status(200).send(JSON.stringify(arrResponse));
} else {
var params = {
to: body.email,
subject: body.subject,
html: body.message
};
transporter.sendMail(params, (mailError, mailReponse) => {
if (mailError) {
var arrResponse = {'status':'failure', 'error': mailError};
} else {
var arrResponse = {'status':'success', 'data': mailReponse.accepted};
}
response.status(200).send(JSON.stringify(arrResponse));
});
}
});
});
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
var http = require('http'),
express = require('express'),
nodemailer = require('nodemailer'),
parser = require('body-parser'),
util = require('util'),
validator = require('express-validator');
// Setup App
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.use(validator());
// Email transporter configuration
var transporter = nodemailer.createTransport({
host: '<host>', //smtp.gmail.com
port: <port>, // secure:true for port 465, secure:false for port 587
secure: true,
auth: {
user: '<email address>',
pass: '<password>'
}
});
// Route
app.post('/email/send', function(request, response){
var body = request.body;
request.checkBody('email', 'Please enter email address').notEmpty();
request.checkBody('email', 'Please enter valid email address').isEmail();
request.checkBody('subject', 'Please enter subject').notEmpty();
request.checkBody('message', 'Please enter messaage').notEmpty();
request.getValidationResult().then(function(result) {
if (!result.isEmpty()) {
var arrResponse = {'status':'error', 'data':util.inspect(result.array())}
response.status(200).send(JSON.stringify(arrResponse));
} else {
var params = {
to: body.email,
subject: body.subject,
html: body.message
};
transporter.sendMail(params, (mailError, mailReponse) => {
if (mailError) {
var arrResponse = {'status':'failure', 'error': mailError};
} else {
var arrResponse = {'status':'success', 'data': mailReponse.accepted};
}
response.status(200).send(JSON.stringify(arrResponse));
});
}
});
});
// Create NodeJs Server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
|
Server is ready not open command-line or temrinal and navigate to applications root directory. Now, start node server using below command:
1
|
$ node app.js
|
Test application by sending request to http://localhost:8080/email/send
URL using postman chrome extension. You can send request to the endpoint using jQuery, AngularJS or other JavaScript frameworks as well.
Read More:
Create RESTful API Using Node.JS, Express and MySQL
Create a RESTFul API Using Node.JS, Express.JS and MongoDB Database
Create a RESTful Web Service API with Slim
How to Create Database in MongoDB
Integrate PayUMoney Payment gateway in PHP
How To Integrate Stripe Payment Gateway Using PHP and JavaScript
sSwitch – JQuery Toggle Button Plugin For Sliding Toggle Switches