Introduction
Sending emails is an important feature of many web applications. Websites use emails to welcome new users, verify email addresses, reset passwords, send order confirmations, and deliver notifications.
Node.js allows developers to implement these features using packages such as Nodemailer. Nodemailer provides a simple way to create email messages and send them through an SMTP server or another supported transport.
What Is Nodemailer in Node.js?
Nodemailer is a Node.js module used to send email messages from server-side JavaScript applications.
It provides methods for configuring an email transport, defining message details, and submitting emails to an email service. Instead of implementing the email-sending process from scratch, developers can use Nodemailer to manage much of the underlying communication.
For example, a Node.js application can use Nodemailer to send a welcome email after a user creates an account.
Why Is Nodemailer Used?
Nodemailer is useful for several reasons:
- It simplifies sending emails from Node.js applications.
- It supports SMTP-based email delivery.
- It can send plain-text and HTML emails.
- It supports file attachments.
- It works with asynchronous JavaScript.
- It provides message information and error details.
- It can be integrated into Express applications and other Node.js backends.
How Does Nodemailer Work?
Nodemailer connects your application to a configured email transport. When your code calls sendMail(), Nodemailer submits the message through that transport.
The email provider then processes the message and attempts to deliver it to the recipient.
The general workflow is:
- The Node.js application creates an email message.
- Nodemailer configures and uses a transport.
- The application submits the message to the email service.
- The email service processes the message.
- The recipient’s email provider handles delivery.
A successful submission does not necessarily mean the message has reached the recipient’s inbox. Delivery can still fail or the email may be filtered as spam.
Prerequisites
Before using Nodemailer, you should have:
- Node.js installed on your computer.
- Basic knowledge of JavaScript.
- npm installed with Node.js.
- An SMTP account or another supported email transport.
- Valid credentials and permission to use the configured sender address.
You can check whether Node.js and npm are installed by running:
node -v
npm -v
These commands display the installed versions.
Step 1: Create a Node.js Project
Create a folder for your project and open it in the terminal.
mkdir nodemailer-demo
cd nodemailer-demo
Initialize the project using npm:
npm init -y
This command creates a package.json file that stores project information and dependencies.
Step 2: Install Nodemailer
Install Nodemailer using the following command:
npm install nodemailer
After installation, Nodemailer will be available in your project.
Create a JavaScript file named index.js. You will write the email-sending code in this file.
Step 3: Configure Nodemailer
Nodemailer uses a transporter to connect to an email service. You can create one using nodemailer.createTransport().
The following example shows a basic SMTP transporter:
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: process.env.SMTP_SECURE === "true",
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
Explanation of the Code
- require(“nodemailer”) imports the Nodemailer package.
- createTransport() creates the transporter.
- host specifies the SMTP server address.
- port specifies the SMTP connection port.
- secure controls whether the connection uses implicit TLS.
- auth.user contains the SMTP username.
- auth.pass contains the SMTP password or provider-approved credential.
The environment variables must be configured before this code runs.
For many providers, port 465 is used with implicit TLS, while port 587 commonly uses STARTTLS. Follow your provider’s requirements instead of choosing settings arbitrarily.
Step 4: Configure Environment Variables
Avoid writing SMTP credentials directly into your source code.
For local development, install the dotenv package:
npm install dotenv
Create a .env file in your project folder:
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-smtp-username
SMTP_PASS=your-smtp-password
EMAIL_FROM=My Website <verified@example.com>
Replace the sample values with the real SMTP settings supplied by your provider.
At the top of index.js, load the environment variables before creating the transporter:
require("dotenv").config();
const nodemailer = require("nodemailer");
Add .env to your .gitignore file:
.env
node_modules/
This helps prevent accidental exposure of credentials in version control. In production, use your hosting platform’s environment configuration or a secret manager.
Step 5: Send an Email Using Nodemailer
Now, create a complete example that sends a plain-text email.
require("dotenv").config();
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: process.env.SMTP_SECURE === "true",
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
async function sendEmail() {
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "Testing Nodemailer",
text: "Hello! This email was sent using Nodemailer in Node.js."
});
console.log("Message submitted:", info.messageId);
}
sendEmail().catch((error) => {
console.error("Unable to send email:", error.message);
});
Replace recipient@example.com with an email address you can access. Also, make sure the sender address is allowed by your email provider.
Run the program:
node index.js
If the configuration is correct, Nodemailer should return information about the submitted message, including a message ID.
Step 6: Send an HTML Email
Nodemailer supports HTML messages, which are useful when you want to include formatted content, headings, paragraphs, or links.
Add the html property to the message object:
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "Welcome to Our Website",
text: "Welcome! Thank you for joining our website.",
html: `
<h2>Welcome to Our Website!</h2>
<p>Thank you for registering.</p>
<p>We are glad to have you with us.</p>
<a href="https://example.com">Visit Our Website</a>
`
});
Here, text provides the plain-text version, while html provides the formatted version.
Including both formats helps support email clients that cannot display HTML messages.
If you include dynamic data in an HTML email, escape or sanitize untrusted values before inserting them into the template.
Step 7: Send an Email with an Attachment
Nodemailer allows you to attach documents, images, and other supported files.
For example, the following code sends an email with a PDF attachment:
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "Your Invoice",
text: "Please find your invoice attached.",
attachments: [
{
filename: "invoice.pdf",
path: "./files/invoice.pdf"
}
]
});
Understanding the Attachment Properties
- filename specifies the name displayed to the recipient.
- path specifies the local file path.
Make sure the file exists and that the Node.js process has permission to read it.
In production applications, do not allow untrusted users to specify arbitrary server file paths. Check authorization and validate which files may be attached.
Step 8: Verify the SMTP Connection
You can use transporter.verify() to check whether Nodemailer can establish a connection and authenticate with the configured SMTP server.
async function verifyTransporter() {
try {
await transporter.verify();
console.log("SMTP connection is ready.");
} catch (error) {
console.error("SMTP verification failed:", error.message);
}
}
verifyTransporter();
This check can help identify configuration or authentication problems before you attempt to send a message.
However, a successful verification does not guarantee that a particular email will be accepted or delivered. Message-specific restrictions and recipient-server rules may still apply.
Step 9: Handle Errors in Nodemailer
Email sending may fail because of incorrect credentials, network problems, SMTP restrictions, or invalid message details.
Use try…catch to handle errors:
async function sendEmail() {
try {
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "Nodemailer Error Handling",
text: "This is a test email."
});
console.log("Email submitted:", info.messageId);
} catch (error) {
console.error("Email sending failed:", error.message);
}
}
The transporter must be created before this function runs.
For production systems, log useful diagnostic information without recording passwords, tokens, or sensitive message content. Temporary failures may require controlled retries or a background job queue.
Important Nodemailer Methods
The following table describes some commonly used Nodemailer methods.
| Method | Description |
|---|---|
| createTransport() | Creates a configured email transport. |
| sendMail() | Submits an email message through the configured transport. |
| verify() | Checks whether the transport can connect and authenticate where applicable. |
These methods cover much of the basic workflow for sending emails with Nodemailer.
Common Mistakes When Using Nodemailer
| Mistake | Solution |
|---|---|
| Incorrect SMTP host | Check the host supplied by your email provider. |
| Wrong port or TLS settings | Follow the provider’s SMTP configuration instructions. |
| Invalid credentials | Use the correct SMTP credential or supported authentication method. |
| Unverified sender address | Verify the sender or domain if your provider requires it. |
| Missing environment variables | Check that the .env file is loaded before creating the transporter. |
| Missing attachment file | Verify the file path and read permissions. |
| Unhandled errors | Use try…catch or a promise rejection handler. |
| Exposed credentials | Keep secrets out of source code and version control. |
Nodemailer Best Practices
Follow these best practices when using Nodemailer in a real application:
- Protect credentials: Store SMTP passwords and other secrets in environment variables or a secret manager.
- Use a verified sender: Configure an address or domain permitted by your email provider.
- Use secure connections: Follow the provider’s TLS and SMTP authentication requirements.
- Validate recipient addresses: Validate addresses and authorize users before sending emails.
- Prevent abuse: Apply rate limits to contact forms and notification endpoints.
- Handle failures: Log relevant errors and use controlled retries for temporary failures.
- Monitor delivery: Review bounce reports and delivery events when your provider supports them.
- Configure email authentication: Set up SPF, DKIM, and DMARC where appropriate to help protect your sending domain.
- Use a queue for high volume: A background queue can help process messages without delaying normal web requests.
Real-Life Example of Nodemailer
Consider an online shopping application that needs to send an order confirmation after a customer purchases a product.
The application can save the order in its database, prepare an email containing the order number and summary, and use Nodemailer to submit the message through an email provider.
A typical workflow is:
- The customer places an order.
- The server validates the request and records the order.
- The application prepares the confirmation email.
- Nodemailer submits the message.
- The email provider processes delivery.
For important business emails, a background queue and delivery monitoring can make the system more reliable.
Conclusion
Nodemailer makes sending emails from Node.js applications easier by providing a straightforward API for configuring transports and submitting messages.
You can use it to send plain-text emails, HTML messages, and attachments, while verify() helps test the SMTP connection. For production applications, protect credentials, validate user input, handle failures, and monitor delivery results.