Express.js Sending Emails
Many apps send email. A shop sends order receipts. A social site sends welcome messages. A bank sends password reset links. Express apps send email through Nodemailer, a popular package that connects to an email service and delivers messages with a few lines of code.
How Email Delivery Works
An Express app does not deliver email directly to an inbox. The app hands the message to an SMTP server, which works like a post office. SMTP stands for Simple Mail Transfer Protocol. The SMTP server carries the message to the recipient's mail provider. Services such as Gmail, Outlook, SendGrid, Brevo, and Amazon SES all offer SMTP access.
Express route
|
v
Nodemailer (builds the message)
|
v
SMTP server (the post office)
|
v
Recipient mail provider
|
v
Inbox
Install Nodemailer
npm install nodemailer dotenvStore Credentials Safely
Mail credentials belong in the .env file. The code reads them from process.env, and the secrets never appear in the source files.
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=apikey_or_username
SMTP_PASS=your_secret_password
MAIL_FROM="My App <no-reply@myapp.com>"Create a Transporter
The transporter holds the connection details. Create it once in a separate file and reuse it everywhere.
// utils/mailer.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
module.exports = transporter;Port 587 with secure set to false uses STARTTLS, which upgrades the connection to an encrypted one. Port 465 uses secure set to true.
Send a Welcome Email
const express = require('express');
const transporter = require('./utils/mailer');
const app = express();
app.use(express.json());
app.post('/register', async (req, res) => {
const { name, email } = req.body;
try {
await transporter.sendMail({
from: process.env.MAIL_FROM,
to: email,
subject: 'Welcome to My App',
text: 'Hi ' + name + ', your account is ready.',
html: '<h1>Welcome, ' + name + '</h1><p>Your account is ready.</p>'
});
res.status(201).json({ message: 'Registered. Check your inbox.' });
} catch (err) {
res.status(500).json({ error: 'Email could not be sent' });
}
});
app.listen(3000);Message Fields
| Field | Purpose |
|---|---|
| from | Sender name and address |
| to | One address or a list |
| cc and bcc | Copy recipients, visible or hidden |
| subject | Subject line |
| text | Plain-text version |
| html | Styled version |
| attachments | Files sent with the message |
Add an Attachment
await transporter.sendMail({
from: process.env.MAIL_FROM,
to: 'customer@example.com',
subject: 'Your invoice',
text: 'The invoice is attached.',
attachments: [
{ filename: 'invoice.pdf', path: './files/invoice.pdf' }
]
});Send a Password Reset Link
A reset email carries a link with a short-lived token. The token proves that the person owns the inbox.
const crypto = require('crypto');
app.post('/forgot-password', async (req, res) => {
const token = crypto.randomBytes(32).toString('hex');
const link = 'https://myapp.com/reset?token=' + token;
// Save the token with an expiry time in the database here.
await transporter.sendMail({
from: process.env.MAIL_FROM,
to: req.body.email,
subject: 'Reset your password',
html: '<p>Click <a href="' + link + '">this link</a> within 30 minutes.</p>'
});
res.json({ message: 'If the email exists, a reset link was sent.' });
});The reply stays the same whether or not the address exists. That choice protects user privacy.
Test Without Real Inboxes
Testing with real addresses risks spamming real people. Services like Ethereal and Mailtrap catch test emails in a safe fake inbox. Nodemailer can create a free Ethereal account with the createTestAccount function.
Best Practices
- Send plain text and HTML versions together.
- Respond to the user first and send long email jobs in the background through a queue.
- Catch errors so a mail failure never crashes the route.
- Use a verified sender domain to avoid the spam folder.
- Include an unsubscribe option in marketing messages and send only to people who agreed to receive them.
Real-World Scenario
An online course site sends three messages: a welcome note after sign-up, a receipt after payment, and a reminder before each live class. Each message uses a small template function that fills in the student name and class time. One shared transporter file serves all three, which keeps the mail settings in a single place.
