How to send email notification in node.js?
In this tutorial, we learn how to send EMAIL Notification using NodeJs.
Nodemailer is a module of Node.js which is used for sending Mail.
Install Nodemailer :-
File Name :
npm install nodemailer
Nodemailer features :-
zero dependencies :- A single module with zero dependencies – code is easily auditable
Heavy security.
nicode support to use any characters, including emoji .
Use HTML content, as well as plain text alternative
Add Attachments to messages
Embedded image attachments for HTML content
Secure email delivery using TLS/STARTTLS
SMTP support
nodemailer module is used to send an email in Node.js. First install the nodemailer module from npm.
File Name :
npm install nodemailer
you can include Nodemailer module in any application:
File Name :
var nodemailer = require('nodemailer');
Features of Nodemailer:
File Name :
It supports various features like adding HTML in the mail, Unicode characters, sending attachments with the text, etc.
It uses the simple mail transfer protocol (SMTP).
How to Send an Email
First import this into our application.
var nodemailer = require('nodemailer');
Create Transporter Object: createTransport() method in nodemailer which accepts an object and finally returns a transporter object. This object will be required to send emails.
const transporter = nodemailer.createTransport(transport[, defaults]);
File Name :
const nodemailer = require('nodemailer');
const secure_configuration = require('./secure');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: secure_configuration.EMAIL_USERNAME,
pass: secure_configuration.PASSWORD,
clientId: secure_configuration.CLIENT_ID,
clientSecret: secure_configuration.CLIENT_SECRET,
refreshToken: secure_configuration.REFRESH_TOKEN
}
});
const mailConfigurations = {
from: 'sana@gmail.com',
to: 'mahira@gmail.com',
subject: 'Sending Email using Node.js',
text: 'Hi! There, You know I am using the NodeJS '
+ 'Code along with NodeMailer to send this email.'
};
transporter.sendMail(mailConfigurations, function(error, info){
if (error) throw Error(error);
console.log('Email Sent Successfully');
console.log(info);
});
Example
File Name :
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'sana@gmail.com',
to: 'mahira@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Multiple Receivers
File Name :
var mailOptions = {
from: 'mahtab.habib@gmail.com',
to: 'sana@yahoo.com, mahira@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
html: '<h1>Welcome</h1><p>That was easy!</p>'
}
Example :-
File Name :
app.post('/mail-sent', (req, res) => {
let body = req.body
let me = body.me //sender id
let pass = body.password //sender password
let to = body.to // receiver id
let sub = body.sub //subject name
let text = body.text //body text
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: me,
pass: pass
}
});
var mailOptions = {
from: me,
to: to,
subject: sub,
text: text,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
res.status(200).send({
success: true,
msg: "mail sent"
})
}
});
})
Example Send Email:-
File Name : server.js
// server.js
var express = require('express'),
path = require('path'),
nodeMailer = require('nodemailer'),
bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index');
});
app.post('/send-email', function (req, res) {
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'xxx@xx.com',
pass: 'xxxx'
}
});
let mailOptions = {
from: '"Arham Kalam" <xx@gmail.com>', // sender address
to: req.body.to, // list of receivers
subject: req.body.subject, // Subject line
text: req.body.body, // plain text body
html: '<b>NodeJS Email Tutorial</b>' // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
res.render('index');
});
});
app.listen(port, function(){
console.log('Server is running at port: ',port);
});
app.set('view engine', 'ejs');
app.use(express.static('public'));
We are setting an ejs templating engine for our application. Also, we are serving static files from the public directory.
index.ejs
File Name : views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nodemailer Email Example</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<div class="container"><br />
<h1>Send The Email</h1><br />
<form action="/send-email" method="post">
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="to">To:</label>
<input type="email" class="form-control" name="to">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="subject">Subject:</label>
<input type="text" class="form-control" name="subject">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="body">Body:</label>
<textarea cols="5" rows="5"class="form-control" name="body"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn-success">Send</button>
</div>
</div>
</form>
</div>
</body>
</html>
Previous
Next