Introduction
Sending emails is a common requirement in many web applications. For example, a website may send a welcome email after registration, a password reset link when a user forgets their password, or an order confirmation after a purchase.
Node.js allows developers to send emails from the server using packages such as Nodemailer. Nodemailer makes it easier to connect to an email service using SMTP and send plain-text or HTML messages.
What Is Email Sending in Node.js?
Email sending in Node.js means using server-side JavaScript to send messages to email addresses through an email server or email service.
A Node.js application usually does not deliver an email directly to the recipient’s inbox. Instead, it connects to an SMTP server, submits the message, and lets the email service handle delivery.
Common uses include:
- Sending welcome emails after user registration.
- Sending password reset links.
- Sending order confirmations and payment receipts.
- Sending notifications and account alerts.
- Sending contact form messages.
What Is Nodemailer?
Nodemailer is a popular Node.js package used to send emails from Node.js applications. It supports SMTP and other transport options, along with plain-text messages, HTML content, attachments, and more.
Some useful features of Nodemailer include:
- Sending plain-text and HTML emails.
- Connecting to SMTP email servers.
- Supporting email attachments.
- Configuring sender, recipient, subject, and message content.
- Handling email-sending errors.
Prerequisites
Before getting started, make sure you have:
- Node.js installed on your system.
- Basic knowledge of JavaScript.
- A code editor such as Visual Studio Code.
- Access to an SMTP service or email provider.
- The required SMTP credentials or authentication method.
You can use an email provider’s SMTP service or a dedicated email delivery service. The correct host, port, and authentication details depend on your provider.
Step 1: Create a Node.js Project
First, create a new folder for your project and open it in your terminal.
mkdir node-email-demo
cd node-email-demo
Initialize the Node.js project:
npm init -y
This command creates a package.json file that stores your project’s configuration and dependencies.
Step 2: Install Nodemailer
Install Nodemailer using npm:
npm install nodemailer
After installation, Nodemailer will be added to your project’s dependencies.
Step 3: Configure SMTP Settings
To send an email, you need an SMTP server. SMTP stands for Simple Mail Transfer Protocol. It is a standard protocol used to send email messages between systems.
Your email provider will supply the SMTP settings. These commonly include:
| Setting | Description |
|---|---|
| SMTP Host | The address of the email server |
| SMTP Port | The port used to connect to the server |
| Username | The account or identifier used for authentication |
| Password | An app password, SMTP credential, or other provider-approved secret |
| Security | TLS or STARTTLS settings required by the provider |
For example, an SMTP provider may require port 465 for an implicit TLS connection or port 587 for a STARTTLS connection. Always follow the provider’s instructions.
Important: Do not assume your regular email account password will work. Some providers require an app password, an SMTP-specific credential, or OAuth authentication.
Step 4: Send an Email with Node.js
Create a file named sendEmail.js in your project folder.
The following example demonstrates the basic Nodemailer workflow. It expects SMTP configuration to be supplied through environment variables.
const nodemailer = require("nodemailer");
async function sendEmail() {
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
}
});
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "My First Email from Node.js",
text: "Hello! This email was sent using Node.js and Nodemailer."
});
console.log("Email submitted:", info.messageId);
}
sendEmail().catch((error) => {
console.error("Unable to send email:", error.message);
});
Understanding the Code
- require(“nodemailer”) imports the Nodemailer package.
- createTransport() creates a transporter using the SMTP settings.
- host identifies your SMTP server.
- port specifies the SMTP port.
- secure controls whether the connection uses implicit TLS. For port 587, this is commonly false, with STARTTLS negotiated by the client and server.
- auth supplies the credentials required by the email provider.
- sendMail() submits the email message.
- from specifies the sender address, which must be permitted by your provider.
- to specifies the recipient.
- subject defines the email subject.
- text contains the plain-text message.
- messageId identifies the submitted message in Nodemailer’s result.
Replace the example recipient with an address you control for testing. The example will not work until valid SMTP configuration and a permitted sender address are provided.
Step 5: Set SMTP Credentials Using Environment Variables
SMTP credentials should not be written directly into your JavaScript source code. Environment variables help keep configuration separate from your application code.
For local development, you can install dotenv:
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=Your App <verified-sender@example.com>
Replace the sample values with the settings provided by your email service.
At the beginning of sendEmail.js, add:
require("dotenv").config();
const nodemailer = require("nodemailer");
Keep the rest of the email-sending code from Step 4 below these lines.
Make sure .env is listed in .gitignore so that secrets are not accidentally committed to version control:
.env
node_modules/
In production, configure environment variables through your hosting platform or secret-management system rather than uploading a development .env file.
Step 6: Run the Node.js Email Program
After configuring the SMTP details, run the program:
node sendEmail.js
If the SMTP connection and authentication succeed, Nodemailer should return a message ID.
A successful sendMail() result means the email service accepted the message for processing. It does not guarantee that the message reached the recipient’s inbox. Delivery can still be affected by spam filters, recipient-server rules, or other delivery issues.
If sending fails, check the error message and verify the SMTP host, port, credentials, sender permissions, and connection settings.
Step 7: Send an HTML Email
HTML emails allow you to format messages with headings, paragraphs, links, and other elements.
You can 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 creating an account.</p>
<p>We are happy to have you with us.</p>
<a href="https://example.com">Visit Our Website</a>
`
});
In this example:
- text provides a plain-text version of the email.
- html provides the formatted version.
- The email client may display the HTML version when it supports HTML email.
Including both versions helps recipients whose email clients do not display HTML content.
Security tip: Do not insert untrusted user input directly into HTML email templates. Escape or sanitize dynamic values to prevent unwanted HTML or script-like content from being included in messages.
Step 8: Send an Email with an Attachment
Nodemailer also supports file attachments. For example, you can attach a PDF invoice to an email.
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"
}
]
});
In this example, filename specifies the name shown to the recipient, while path points to the file on the server.
Make sure the file exists and that the application has permission to read it. For user-uploaded files, validate access and file paths carefully, and do not allow a user to attach arbitrary server files.
Step 9: Handle Email-Sending Errors
Email sending may fail because of invalid credentials, network problems, rejected sender addresses, or SMTP configuration errors.
Using try…catch makes it easier to handle errors:
async function sendEmail() {
try {
const info = await transporter.sendMail({
from: process.env.EMAIL_FROM,
to: "recipient@example.com",
subject: "Node.js Email Test",
text: "This is a test email."
});
console.log("Email submitted:", info.messageId);
} catch (error) {
console.error("Email sending failed:", error.message);
}
}
The transporter variable must be created before this function runs, using the SMTP configuration shown earlier.
For production applications, log enough information to diagnose failures without exposing passwords, tokens, or other sensitive information. You may also need retry handling for temporary failures and a queue for high-volume email sending.
Common Mistakes When Sending Email with Node.js
| Mistake | How to Avoid It |
|---|---|
| Using the wrong SMTP host | Copy the host from your email provider’s documentation. |
| Using an incorrect port | Check whether your provider requires port 465, 587, or another port. |
| Using the wrong security setting | Match secure and TLS settings to the provider’s instructions. |
| Using an invalid password | Use the correct SMTP credential, app password, or supported authentication method. |
| Using an unverified sender | Verify the sender address or domain with your email provider. |
| Hardcoding credentials | Store secrets in environment variables or a secret manager. |
| Ignoring errors | Handle rejected messages and connection failures. |
Security Best Practices
Follow these practices when implementing email sending in a real application:
- Protect credentials: Never commit SMTP passwords, API keys, or tokens to a public repository.
- Validate input: Validate recipient addresses and any user-provided fields before sending messages.
- Prevent email abuse: Apply rate limits and authorization checks to contact forms and notification endpoints.
- Use a trusted provider: Choose a provider that supports appropriate authentication and transport encryption.
- Verify sender domains: Configure SPF, DKIM, and DMARC where supported to help protect your domain’s email reputation.
- Avoid exposing sensitive information: Do not include passwords, access tokens, or private user data in logs or email content unnecessarily.
- Monitor delivery: Review bounces, complaints, and delivery reports to identify problems.
- Use queues for larger workloads: A background job queue can help manage retries and avoid slowing down normal application requests.
Real-Life Example of Sending Email with Node.js
Imagine you are building an online shopping website. When a customer places an order, the application needs to send an order confirmation.
The workflow might look like this:
- The customer places an order.
- The Node.js server saves the order in the database.
- The application creates an email containing the order number and summary.
- Nodemailer submits the message through the configured email service.
- The email provider processes delivery and may report delivery failures.
In a production application, send the confirmation only after the order has been successfully recorded. For important business emails, a background queue and delivery monitoring can make the process more reliable.
Conclusion
Sending email with Node.js becomes straightforward when you use Nodemailer. You can configure an SMTP transporter, send plain-text or HTML messages, attach files, and handle errors with a small amount of JavaScript.
For production applications, keep credentials secure, use a verified sender, validate user input, and monitor delivery results. These practices will help you build a more reliable email feature for registration, password resets, notifications, and other application workflows.