NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How to send EMAIL using NodeJs?
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 :-
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>
File Name :