How to Send Email using NodeJS?
Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for sending emails from NodeJS.
What We Are Going to Create?
We will create a simple application that allows you to send emails using NodeJS. The application will feature:
- Sending plain text and HTML emails.
- Sending emails with attachments.
- Customizing the sender, recipient, subject, and body of the email.
Project Preview
In this project, we will create a simple web interface where the user can fill out an email form and send an email through a NodeJS server.

Approach
Below are the steps to follow for building an email-sending system using NodeJS
- Install Nodemailer: Nodemailer is the main module we will use to send emails.
- Create an Email Sending Route: Define a route to handle the email-sending process.
- Set Up SMTP Service: We'll use an SMTP (Simple Mail Transfer Protocol) service for sending emails.
- Handle Email Input: Capture user input (like recipient, subject, and message) using the body parser.
- Send the Email: Use Nodemailer to send the email.
Steps to Build the Email Sending System Using NodeJS
Step 1: Create a Project Folder
Open your terminal (Command Prompt/PowerShell) and run the following commands
mkdir email-sending-system
cd email-sending-system
Step 2: Initialize a NodeJS Project
Run the following command to create a package.json file
npm init -y
Step 3: Install Dependencies
Run the following command to install the required dependencies
npm install express nodemailer body-parser
This installs
- Express: Backend framework to handle routing.
- Nodemailer: Module for sending emails.
- Body-parser: Middleware to handle form submissions.
Step 4: Create Server File
Create a file named app.js and require the necessary modules. Then, create an Express instance and set up body-parser to capture form data.
const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('home');
});
// Handle email sending
app.post('/send-email', (req, res) => {
const { recipient, subject, message } = req.body;
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your gmail',
pass: 'your password'
}
});
// Define the email options
const mailOptions = {
from: 'sender mail',
to: recipient,
subject: subject,
text: message,
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error occurred:", error);
res.status(500).send('Error in sending email. Please try again later.');
} else {
console.log('Email sent:', info.response);
res.send('Email sent successfully!');
}
});
});
app.listen(PORT, () => {
console.log(`App is running on port ${PORT}`);
});
In this code
- Express Setup: Uses Express to handle HTTP requests and route them.
- Nodemailer: Sends emails via Nodemailer using Gmail's SMTP service.
- Body-Parser Middleware: Body-parser parses form data from POST requests.
- EJS for Dynamic Pages: EJS is used to render HTML templates dynamically with form input.
- Form Handling and Error Response: Form data is processed, and email is sent; success or error messages are returned to the user.
Step 5: Enable an App Password in Gmail
- Before you can generate an App Password, you need to have 2FA enabled on your Google account. If you haven’t done this already, follow these steps:
- Go to Google Account Settings and enable 2-Step Verification
- Generate the App Password after enabling 2FA, you can now generate an App Password.
- In the Security section of your Google Account, find App Passwords (under "Signing in to Google").
- You might be asked to log in again to verify your identity.
- Create a New App Password
- Once logged in, select Other (Custom name) from the "Select app" dropdown.
- Type a name (e.g., NodeMailer App) to identify this password later.
- Google will generate a 16-character App Password (e.g., abcd efgh ijkl mnop).
- Copy this password and keep it safe. You will use this password in your Nodemailer configuration.
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com', // Your Gmail address
pass: 'your-app-password' // The App Password generated above
}
});
Step 5: Create the Home Page (home.ejs)
Create a views folder in your root directory, and inside it, create a file called home.ejs. Inside views/home.ejs, add the following code
<html>
<body>
<h1>Send Email</h1>
<form action="/send-email" method="POST">
<label for="recipient">Recipient:</label>
<input type="email" name="recipient" id="recipient" required><br>
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required><br>
<label for="message">Message:</label><br>
<textarea name="message" id="message" rows="5" cols="50" required></textarea><br>
<button type="submit">Send Email</button>
</form>
</body>
</html>
Output:
node app.js
Conclusion
In this article, we have successfully built a simple email-sending system using NodeJS with Nodemailer. This system allows users to send both plain text and HTML emails with customizable fields such as the recipient, subject, and message. We also covered the necessary steps to handle form submissions using Express and body-parser, ensuring that user input is processed and sent via an SMTP service.
By using Nodemailer, we enabled the application to send emails through Gmail (or any SMTP server) by configuring it with appropriate authentication credentials. Additionally, we also discussed how to handle errors effectively and provide user feedback on whether the email was successfully sent or if there was an issue.