Sending email
suggest changeNode.js applications frequently need to send transactional emails, such as account verification links, password reset tokens, order receipts, and system alerts. The industry standard library for email delivery in Node.js is Nodemailer.
1. Getting Started with Nodemailer
Install Nodemailer using npm:
npm install nodemailer
Nodemailer operates around two core concepts:
- Transporter: The delivery mechanism (SMTP server, cloud email service, or local sendmail).
- Mail Options: The message payload, including headers, recipients, plain text, HTML body, and attachments.
2. Testing Emails Locally with Ethereal Email
During development, you should avoid sending test emails to real addresses. Nodemailer integrates with Ethereal Email, a fake SMTP service that captures messages and generates web preview URLs.
import nodemailer from 'nodemailer';
async function sendTestEmail() {
// Generate a free disposable test account on Ethereal
const testAccount = await nodemailer.createTestAccount();
// Create reusable transporter using the generated credentials
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user,
pass: testAccount.pass,
},
});
// Send mail
const info = await transporter.sendMail({
from: '"My Application" <noreply@example.com>',
to: 'user@example.com',
subject: 'Welcome to Our Platform!',
text: 'Hello! Thank you for registering.',
html: '<b>Hello!</b><p>Thank you for registering with our platform.</p>',
});
console.log('Message sent: %s', info.messageId);
// Preview URL available only when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
}
sendTestEmail().catch(console.error);
3. Production SMTP Configuration
In production environments, configure SMTP credentials via environment variables:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT) || 587,
secure: Number(process.env.SMTP_PORT) === 465, // true for 465, false for STARTTLS
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
pool: true, // Use pooled connections for high volume
maxConnections: 5,
maxMessages: 100,
});
// Verify connection configuration on startup
transporter.verify((error, success) => {
if (error) {
console.error('SMTP connection failed:', error);
} else {
console.log('Server is ready to deliver messages');
}
});
4. Sending Attachments and Embedded Images
Nodemailer supports sending files from the filesystem, URLs, or in-memory Buffers, as well as embedding images directly into HTML via Content-ID (cid):
import nodemailer from 'nodemailer';
import path from 'node:path';
async function sendInvoice(recipientEmail, invoicePdfBuffer) {
const mailOptions = {
from: '"Billing Department" <billing@example.com>',
to: recipientEmail,
subject: 'Your Monthly Invoice',
html: `
<h2>Invoice Attached</h2>
<p>Thank you for your business. Please find your invoice attached below.</p>
<img src="cid:companyLogo" alt="Company Logo" width="120" />
`,
attachments: [
{
filename: 'invoice-2026-10.pdf',
content: invoicePdfBuffer,
contentType: 'application/pdf',
},
{
filename: 'logo.png',
path: path.join(process.cwd(), 'assets', 'logo.png'),
cid: 'companyLogo', // Referenced in the img tag src
},
],
};
const info = await transporter.sendMail(mailOptions);
return info;
}
5. Templating and HTML Emails
For rich emails, render HTML dynamically using template engines or modern components. Here is an example combining a simple template function with Nodemailer:
function renderWelcomeTemplate(username, verificationUrl) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: sans-serif; line-height: 1.6; color: #333; }
.button { display: inline-block; padding: 10px 20px; background: #007bff; color: #fff; text-decoration: none; border-radius: 4px; }
</style>
</head>
<body>
<h2>Hello, ${username}!</h2>
<p>Please confirm your email address by clicking the button below:</p>
<p><a href="${verificationUrl}" class="button">Verify Email</a></p>
<p>If you did not create an account, please ignore this email.</p>
</body>
</html>
`;
}
async function sendWelcomeEmail(user) {
const html = renderWelcomeTemplate(user.name, user.verifyUrl);
return transporter.sendMail({
from: '"Acme App" <auth@example.com>',
to: user.email,
subject: 'Confirm your email address',
text: `Hello ${user.name},\n\nPlease confirm your email: ${user.verifyUrl}`,
html: html,
});
}
6. Best Practices
- Never Hardcode Secrets: Always load SMTP hosts, ports, and API keys from environment variables.
- Provide Plain Text Fallbacks: Always specify the
textfield alongsidehtmlfor accessibility and spam score optimization. - Asynchronous Background Processing: Avoid awaiting
sendMail()directly inside HTTP request handlers. Offload email delivery to background job queues (e.g., BullMQ, RabbitMQ, or AWS SQS) to prevent HTTP latency and handle retries gracefully. - Deliverability & Authentication: Configure DNS records for your sending domain, including SPF, DKIM, and DMARC, to prevent emails from landing in spam folders.