How to send email using Node.js and Nodemailer?

Hello everyone, today we will learn how to send email using Node.js and Nodemailer. Here I am using the Nodemailer module to send an email. Nodemailer is a module for Node.js applications to send the email easily. 


You will need to have Node.js and npm (Node Package Manager) installed locally. You can install these packages from Node.js' official website.

Getting Started

Install Nodemailer using the following command.

npm install nodemailer

After you have downloaded the Nodemailer module, you can include the module in your application:

var nodemailer = require('nodemailer');

Now we are ready to send emails from your server. Use the username and password from your selected email provider to send an email.

This is a complete example to send an email with plain text and HTML body.

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '',
pass: 'password'

var mailFactory = {
from: '',
to: '',
subject: 'Greetings from Node.js',
html: '<h1 style="color:green;">Welcome</h1><p>Node.js is easy</p>'

transporter.sendMail(mailFactory, function(error, info){
if (error) {
} else {
console.log('Email sent: ' + info.response);

This is a complete example to send an email with plain text.

A package. json is a JSON file that subsists at the root of a Javascript/Node project. It holds metadata pertinent to the project and it is utilized for managing the project's dependencies, scripts, version and a whole lot more.

"name": "node_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon index.ts"
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^14.0.1",
"nodemailer": "^6.4.16",
"ts-node": "^8.10.1",
"typescript": "^3.9.2"
"devDependencies": {
"nodemon": "^2.0.3"

Execute our application using the following command,

npm start

Console output:

[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node index.ts`
Email sent: 250 2.0.0 OK  1606580657 o67sm10831411pfb.109 - gsmtp
[nodemon] clean exit - waiting for changes before restart


✌Happy coding

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example