How do I send emails from a Node.js app with Nodemailer and SMTP?
Install Nodemailer, build an SMTP transport from environment variables and call sendMail from the server, using port 587 with secure: false or 465 with secure: true. Send from your own domain with SPF, DKIM and DMARC set up.
To send email from your Node app with Nodemailer and SMTP, install Nodemailer, create an SMTP transport with host, port, user and password read from environment variables, and call sendMail from the server. Use port 587 with secure: false (STARTTLS) or 465 with secure: true (TLS). Send from your domain with SPF, DKIM and DMARC configured.
What you need before you start
You need a Node.js project with ES modules ("type": "module" in your package.json) and the details of an SMTP account: server, port, user and password. If you want to review how an email travels between servers, read what SMTP is and how it works. To understand why SMTP is for sending and not for reading the mailbox, see the difference between SMTP, POP and IMAP.
Step-by-step recipe with Nodemailer
1. Install the library
npm install nodemailer express2. Define the environment variables
The following names are just examples; you can use others as long as they match your code:
SMTP_HOST=mail.yourdomain.com
SMTP_PORT=587
SMTP_USER=contact@yourdomain.com
SMTP_PASS=your-password
MAIL_FROM=contact@yourdomain.comThis file is not committed to the repository. In production, these values are set as server environment variables.
3. Create the transport and verify the connection
// mailer.js
import nodemailer from 'nodemailer';
const port = Number(process.env.SMTP_PORT);
export const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port,
secure: port === 465, // 465 = direct TLS; 587 = STARTTLS
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
export async function probarSmtp() {
try {
await transporter.verify();
console.log('SMTP connection OK');
} catch (err) {
console.error('SMTP error:', err.message);
}
}transporter.verify() connects to the server and tries to authenticate without sending any email. Use it when the app starts or in a test to catch configuration errors early.
4. Send the email from an Express route
// server.js
import express from 'express';
import { transporter, probarSmtp } from './mailer.js';
const app = express();
app.use(express.json());
app.post('/contacto', async (req, res) => {
const { nombre, email, mensaje } = req.body;
if (!email || !mensaje) {
return res.status(400).json({ ok: false, error: 'Missing data' });
}
try {
await transporter.sendMail({
from: process.env.MAIL_FROM,
to: process.env.MAIL_FROM,
replyTo: email,
subject: `New message from ${nombre || 'website contact'}`,
text: `From: ${email}\n\n${mensaje}`,
html: '<p>You have a new message from the contact form.</p>',
});
res.json({ ok: true });
} catch (err) {
console.error('Could not send:', err.message);
res.status(500).json({ ok: false, error: 'The message could not be sent' });
}
});
app.listen(process.env.PORT || 3000, probarSmtp);The browser form only makes a fetch to POST /contacto. The SMTP connection and the password always stay on the server and never reach the frontend.
Best practices
- Sender on your domain: the
fromfield must be an address on your domain. If you want to reply to the person who wrote, put their address inreplyTo, not infrom. - SPF, DKIM and DMARC: SPF states which servers can send on behalf of your domain, DKIM signs each message and DMARC tells receivers what to do if something doesn't match. Without these records, your emails can land in spam.
- Credentials out of the code: never write the SMTP password in the code, in the repository or in variables that end up in the frontend.
- Controlled errors: wrap the send in
try/catch, log the error and respond to the user. Don't retry in a loop, because repeated authentication failures can lock the account. - Validate the input: check the form fields before sending and don't put unescaped user text inside the email's HTML.
Common errors and how to fix them
| Symptom | Likely cause | Fix |
|---|---|---|
| Timeout or TLS error when connecting | Port and secure mismatched | 587 with secure: false; 465 with secure: true |
| Authentication error | Wrong user or password | Use the full address as the user and check the password variable |
| The email lands in spam | SPF, DKIM or DMARC missing, or the from isn't on your domain | Set up the domain records and send from your own address |
From Dongee Live
Dongee Live, Dongee's hosting for AI-built apps, publishes Node.js apps (Express, Fastify, Koa, Hono, Next.js and others) made with Claude Code, Cursor, Codex, Lovable, Bolt or v0. From Live, outbound SMTP works on ports 587 and 465, so this recipe works as is. You define your app's environment variables, including on Live Free, and Live keeps the app running with HTTPS.
The mailbox included with your Live plan is a normal email account with the usual sending limits. It's suited to low volume, such as a contact form or occasional notices. If your app sends transactional email to many users (sign-up confirmations, password resets), it's better to use MailChannels, which is contracted separately and works from Live. If you want to know how this kind of sending works, read what an SMTP relay is.
Honest comparison: included mailbox or transactional service
| Criterion | Mailbox included with Live | Transactional service (MailChannels) |
|---|---|---|
| Cost | Included in the plan | Contracted separately |
| Volume | Low, with the normal limits of an email account | Designed for frequent sending from the app |
| Use cases | Contact form, occasional notices | Confirmations, password resets, notifications to many users |
| Mass campaigns | No | No: Live isn't designed for mass campaigns |
When Dongee Live isn't a good fit: if your goal is to send mass email marketing campaigns, Live isn't designed for that. It also doesn't work if your backend is in Python, PHP or Docker. PHP and WordPress go on Dongee's cPanel hosting, and Python and Docker on Dongee Cloud.
Frequently asked questions
Should I use port 587 or 465?
Both encrypt the connection. Port 587 starts in plain text and upgrades to encryption with STARTTLS, which is why it uses secure: false. Port 465 encrypts from the start and uses secure: true. Choose the one your email provider specifies.
Can I use Gmail as an SMTP server?
It depends on that provider's terms and authentication requirements. In any case, for an app with your own domain it's better to send from an address on that domain.
Does this code work in Next.js?
Yes, as long as it runs in server code, such as an API route or a server action, and never in a client component. You'll find the step-by-step in the guide to publishing a Next.js app from Bolt or v0 with SMTP email.
Why not send the email directly from the browser?
Because you'd have to expose the SMTP password in the frontend, and anyone could use it to send email in your name. The browser should only call your server route.
Can I send newsletters to my whole list from Live?
No. The included mailbox is for low-volume email, and Live isn't designed for mass campaigns. For transactional email to many users, use MailChannels.
Summary
With Nodemailer, environment variables and a server route, sending is solved in a few lines. Match the port with secure correctly, send from your domain with SPF, DKIM and DMARC configured, and choose the included mailbox or a transactional service based on your app's real volume.
Comenta lo que quieras
Unete a la charla
Solo ingresa tu email