How to Send Email using Node.js ?
Last Updated :
11 Sep, 2024
Sending emails is a common task in many applications, whether it be for sending notifications, account verification, password resets, or other communication needs.
In this article, we’ll explore how to send emails using Node.js. We will cover setting up a mail transport, composing the email, and sending it.
Approach
To send email using node, we will use the nodemailernpm package. Use the createTransporter method to configure the transpoter with SMTP settings, define the sender, message and recipient and then use sendMail methods to send the mail.
Why Use Node.js for Sending Emails?
Node.js provides a powerful and flexible environment for sending emails. It supports various email protocols, can handle asynchronous tasks efficiently, and integrates well with popular email services like Gmail, SendGrid, and Mailgun. By using Node.js for sending emails, you can:
- Leverage Asynchronous Operations: Send emails without blocking other operations in your application.
- Integrate Seamlessly: Use libraries that integrate with various email services and protocols.
- Handle Large Volumes: Efficiently send large volumes of emails with appropriate configuration.
Nodemailer
There are various modules available for sending emails but the nodemailer is the most popular one and it provides us simple procedure and functionality to send mail.
Features of Nodemailer
- 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). Below is the step-by-step approach to be followed to integrate this module into our application.
Configure Nodemailer to Send Email
Step 1: Module Installation
Write the command in the terminal to install nodemailer and then import at the top of your nodejs application.
npm install nodemailer
Now we are ready to import this into our application.
const nodemailer = require('nodemailer');Step 2: Create Transporter Object
There exists a createTransport method in nodemailer which accepts an object with some configurations and finally returns a transporter object. This object will be required later to send emails.
const transporter = nodemailer.createTransport(transport[, defaults]);
Here we are using Gmail as a service just for sample purposes, Although nodemailer can be easily integrated with any other mail service. In Gmail, we can either make our account less secure or we can use the Oauth2 security authentication unless normally google will not allow sending any mail via node.js.
Less Secure Account
Visit this link to make your account less secure, after doing this we can create our working transporter object just with the username and password of your Gmail account.
Node
// app.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: secure_configuration.EMAIL_USERNAME,
pass: secure_configuration.PASSWORD
}
});
Using Oauth2 to congifure mail account
According to official docs here we need to provide client id, client secret, refresh token, and an access token along with the username and password. Follow the step-by-step approach to get these configurations from the google cloud console.
Step 1: Open Google Cloud Console
In this step, we will get our client id and client secret. Visit the google cloud console website and register/sign in yourself. Then proceed to API & Services section from the leftmost navigation bar. Now check out the dashboard and create a project. After this, visit the Oauth consent screen to register about your application in this step make sure to select user type external and add some/one Test Users. After this step, go to the credentials section and click on Create credentials and then choose Oauth2 ClientID and choose application type as a web application, also make sure to add redirect URI as OAuth playground (copy link from here). Finally, you’ll be successful to get your client_id and client_secret.
Step 2: Open the Oauth2 Playground
Here we will get our refresh token and access token. Visit the OAuth2 playground, Click on the oauth2.0 configuration icon from the right and then check the use your own credentials checkbox and provide the same client id and secret you’ve got from the cloud console. Now select the Gmail API for authorization. Click on Authorize API and then authorize it by the same Gmail id you have been filled as a test user in the credentials section of the last step. Finally, click on the exchange authorization code for tokens and this will provide a refresh token and access token.
Note: We suggest you open these gifs in a separate tab and follow both approaches separately and don’t skip at any span this would save you from a lot of confusion, Also don’t try to copy this client id and client secret, etc. it will not going to work.
Node
// app.js
const nodemailer = require('nodemailer');
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
}
});
With this our transporter object is ready and now we can send our emails.
Step 3: Configure eMail
Before sending the mail we have to create some message configurations like what to send where to send etc. It is super easy to create these configurations there are several key-value pairs, from which you can provide the required ones along with some other values to the predefined key.
Sending a simple text to one email
Node
// app.js
const mailConfigurations = {
// It should be a string of sender email
from: 'mrtwinklesharma@gmail.com',
// Comma Separated list of mails
to: 'smtwinkle451@gmail.com',
// Subject of Email
subject: 'Sending Email using Node.js',
// This would be the text of email body
text: 'Hi! There, You know I am using the'
+ ' NodeJS Code along with NodeMailer '
+ 'to send this email.'
};
Output: If we send the email with these configurations, something like this will be sent to the receiver. Although our code is currently incomplete, here we are just showing you how this message configuration will look like when the code will be completed.

Sending to Multiple emails:
We can concatenate more emails with a comma as a separator.
Node
const mailConfigurations = {
from: 'mrtwinklesharma@gmail.com',
to: 'smtwinkle451@gmail.com, anyothergmailid@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.'
};
Sending some HTML content
Just replace the Plain text with HTML and provide it to HTML key.
JavaScript
const mailConfigurations = {
from: 'mrtwinklesharma@gmail.com',
to: 'smtwinkle451@gmail.com',
subject: 'Sending Email using Node.js',
html: "<h2>Hi! There</h2> <h5> This HTML content is
being send by NodeJS along with NodeMailer.</h5>"
};
Output:

Sending some Attachments, Nodemailer is so flexible while sending attachments, you can send any type of file which is being accepted by email service.
JavaScript
const mailConfigurations = {
from: 'mrtwinklesharma@gmail.com',
to: 'smtwinkle451@gmail.com',
subject: 'Sending Email using Node.js',
text:'Attachments can also be sent using nodemailer',
attachments: [
{
// utf-8 string as an attachment
filename: 'text.txt',
content: 'Hello, GeeksforGeeks Learner!'
},
{
// filename and content type is derived from path
path: '/home/mrtwinklesharma/Programming/document.docx'
},
{
path: '/home/mrtwinklesharma/Videos/Sample.mp4'
},
{
// use URL as an attachment
filename: 'license.txt',
path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE'
}
]
};
Output:

Not only these but nodemailer have a lot of possibilities for message configurations you can check them all from here.
Step 4: Send eMail
Use any one of the above approaches to proceed with the transporter object, and then choose any one email configurations to send mail.
There exists a sendMail method in the transporter object which accepts email configurations and a callback function that will be executed either when mail has been sent or due to an error.
transporter.sendMail(mailConfigurations[, callback]);
JavaScript
transporter.sendMail(mailConfigurations, function(error, info){
if (error) throw Error(error);
console.log('Email Sent Successfully');
console.log(info);
});
Step 5: Combine them All
You can pick any options from the step 2 and 3. After providing it to the sendMail method you will be successfully able to send an email with node.js.
Explanation
Here we have imported the nodemailer module in the beginning and then used the Oauth2 type of authentication, later there is the most basic message configuration which is being used. Finally, the sendMail method is sending the mail to receivers provided in message configuration.
Note:- The secure module being imported has nothing to do with this nodemailer, I have just used it to secure my credentials.
app.js
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: 'mrtwinklesharma@gmail.com',
to: 'smtwinkle451@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);
});
Output: Run this code snippet with node command and this will be the output in the console and Gmail inbox.
Similar Reads
Web and API Development
How to build Node.js Blog API ?
In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters. Functionalities: Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we
5 min read
RESTful Blogging API with Node and Express.js
Blogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB. Prerequisites:Node JS & NPMExpress JSMongoDBApproach
6 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and
15+ min read
Communication and Social Platforms
Management Systems
Customer Relationship Management (CRM) System with Node.js and Express.js
CRM systems are important tools for businesses to manage their customer interactions, both with existing and potential clients. In this article, we will demonstrate how to create a CRM system using Node.js and Express. We will cover the key functionalities, prerequisites, approach, and steps require
15+ min read
Library Management Application Backend
Library Management System backend using Express and MongoDB contains various endpoints that will help to manage library users and work with library data. The application will provide an endpoint for user management. API will be able to register users, authenticate users, borrow books, return books,
10 min read
How to build Library Management System using Node.js?
In this article, we are going to create a Library Management System. A Library Management System is basically used to manage the book record of a Library, where a librarian can view all the available books, add new books, delete books, issue books, and return books. Note: Follow given link to build
9 min read
Student Management System using Express.js and EJS Templating Engine
In this article, we build a student management student which will have features like adding students to a record, removing students, and updating students. We will be using popular web tools NodeJS, Express JS, and MongoDB for the backend. We will use HTML, CSS, and JavaScript for the front end. We'
5 min read
Subscription Management System with NodeJS and ExpressJS
In this article, weâll walk through the step-by-step process of creating a Subscription Management System with NodeJS and ExpressJS. This application will provide users with the ability to subscribe to various plans, manage their subscriptions, and include features like user authentication and autho
5 min read
Building a Toll Road Management System using Node.js
In this article, we are going to build a simple Toll Road Management System using Node.js, where the data will be stored in a local MongoDB database. Problem Statement: In a toll tax plaza, it is difficult to record all the transactions and store them in a single place, along with that, if required,
15+ min read
How to Build User Management System using Node.js ?
In this article, we are going to create a User Management System. A User Management System is basically used to manage the users of any organization, organizations can View Users, Add Users, Delete Users and Update Users. Prerequisites:Node JSExpress JSApproach To build User Management System We are
8 min read
User Management System Backend
User Management System Backend includes numerous endpoints for performing user-dealing tasks. The backend could be constructed with the use of NodeJS and MongoDB with ExpressJS . The software will offer an endpoint for consumer management. API will be capable of registering, authenticating, and cont
4 min read
File and Document Handling
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume
2 min read
DOCX to PDF Converter using Express
In this article, we are going to create a Document Conversion Application that converts DOCX to PDF. We will follow step by step approach to do it. We also make use of third-party APIs. Prerequisites:Express JS multernpm Preview of the final output: Let us have a look at how the final output will lo
4 min read
How to Send Email using Node.js ?
Sending emails is a common task in many applications, whether it be for sending notifications, account verification, password resets, or other communication needs. In this article, we'll explore how to send emails using Node.js. We will cover setting up a mail transport, composing the email, and sen
8 min read
File Sharing Platform with Node.js and Express.js
In today's digital age, the need for efficient File sharing platforms has become increasingly prevalent. Whether it's sharing documents for collaboration or distributing media files, having a reliable solution can greatly enhance productivity and convenience. In this article, we'll explore how to cr
4 min read
React Single File Upload with Multer and Express.js
When we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files onli
5 min read
Task and Project Management
Task Management System using Node and Express.js
Task Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend inter
15+ min read
Task Manager App using Express, React and GraphQL.
The Task Manager app tool is designed to simplify task management with CRUD operation: creation, deletion, and modification of tasks. Users can easily generate new tasks, remove completed ones, and update task details. In this step-by-step tutorial, you will learn the process of building a Basic Tas
6 min read
Simple Task Manager CLI using Node.js
Before creating a simple Task Manager CLI using NodeJS, let's run our first basic Node.js application with the following simple steps: Note: You can download and install the Node.js application from href="https://nodejs.org/en/" Step 1: Create a Directory for our Task Manager CLI named TODO-CLI, you
4 min read
Task Scheduling App with Node and Express.js
Task Scheduling app is an app that can be used to create, update, delete, and view all the tasks created. It is implemented using NodeJS and ExpressJS. The scheduler allows users to add tasks in the cache of the current session, once the app is reloaded the data gets deleted. This can be scaled usin
4 min read
Todo List CLI application using Node.js
CLI is a very powerful tool for developers. We will be learning how to create a simple Todo List application for command line. We have seen TodoList as a beginner project in web development and android development but a CLI app is something we don't often hear about. Pre-requisites:A recent version
13 min read