There are two email systems, one in each process, configured independently because the processes are separate. You can point both at the same SMTP provider in production.
1. Magic-link emails (frontend / NextAuth)
NextAuth sends sign-in emails through its built-in Nodemailer provider,
configured in frontend/auth.ts from EMAIL_SERVER_HOST,
EMAIL_SERVER_PORT, EMAIL_SERVER_SECURE, EMAIL_SERVER_USER,
EMAIL_SERVER_PASSWORD and EMAIL_FROM. You never call it directly; NextAuth runs it when a user
submits their email, and the send is synchronous because it blocks the
sign-in flow.
Email sign-in is optional as a whole: leave EMAIL_SERVER_HOST unset and
the signin form hides the option. A partial config fails boot in
production instead of silently hiding it. See
Auth Flow for the full sign-in sequence.
2. App emails (backend / EmailService)
backend/src/email/email.service.ts handles transactional and bulk mail.
It sends through the MAIL_TRANSPORT provider (email/mail-transport.ts),
which email.module.ts binds to one pooled Nodemailer transporter
(maxConnections: 5, maxMessages: 100) built at boot. To send through an
HTTP mail API instead, bind that token to anything with
sendMail({ to, subject, html }). The service exposes two entry points,
both of which only insert email_jobs rows:
queue()- queue one email.queueBulk()- queue many at once, for campaigns. Every email is validated before any is inserted, so one bad address queues none.
to is one email address per job. Both methods trim and lowercase it and
throw on anything else, such as a comma-separated list: account erasure
matches to against a single address, so a job listing several would keep
every address when one recipient is erased.
Two settings are checked at boot, so a production deploy with either one wrong fails to start instead of mishandling mail:
SMTP_FROMis required.parseEnv(src/config/env.schema.ts) refuses boot without it rather than sending mail under the wrong identity, or having SMTP servers reject a sender-less envelope.SMTP_PORTgoes throughparseSmtpPort(email/smtp-port.ts), whichparseEnvruns. Unset or empty defaults to1025; anything but an integer from 1 to 65535 throws instead of falling back. A silent fallback would put a real deployment into MailDev mode and drop every outgoing email.
SMTP_USER, when set, adds auth credentials automatically.
Queue and processing
Queued emails become email_jobs rows. EmailProcessor runs on
@Cron(EVERY_30_SECONDS) and calls processBatch(50), which handles up to
50 jobs one at a time. Each job is claimed as PROCESSING and charged an
attempt in the same statement, sent, then marked SENT or FAILED with
exponential backoff. The outcome is written only while that claim still
holds, so a send that outlasts WORKER_CLAIM_STALE_MS cannot overwrite the
worker that took the job over. Delivery is at-least-once: a crash after the
SMTP server accepts the message, or a send that outlives the window, can send
the job again, at most max_attempts times in all. The transport's connect,
greeting and socket timeouts are 1/10, 1/10 and 1/5 of that window, so a
stalled send fails before its job is re-claimed; the socket timeout bounds
inactivity, not total time.
A job left in PROCESSING past that window is claimed again while it has
attempts left. One that spent its last attempt without recording an outcome
is marked FAILED instead, because whether it was delivered is unknown.
An isProcessing flag prevents overlapping batch runs within a process; the
claim is what makes it safe across replicas (see
Architecture).
Admin dashboard
AdminEmailController, guarded by SessionGuard + AdminGuard:
| Route | Description |
|---|---|
GET /admin/email/stats |
Overall stats + per-campaign breakdown + 30-day daily volume + recent failures, as one bundle |
GET /admin/email/campaigns/:id |
Per-campaign detail: send/fail counts, success rate, recent attempts |
Backend SMTP variables are SMTP_HOST, SMTP_PORT, SMTP_SECURE,
SMTP_USER, SMTP_PASS and SMTP_FROM; defaults and requirements are in
Environment Variables.
Sending an email from a service
Import EmailModule in your feature module, then inject EmailService:
import { EmailModule } from 'src/email/email.module';
@Module({ imports: [EmailModule] })
export class YourModule {}
@Injectable()
export class YourService {
constructor(private readonly emailService: EmailService) {}
async doSomething() {
// Inserts an email_jobs row and returns; the worker sends it on its
// next tick and retries a failure with backoff.
await this.emailService.queue({
to: '[email protected]',
subject: 'Something happened',
html: '<h1>Hello</h1><p>Your thing is ready.</p>',
});
}
}
Backend mail always goes through the queue: queue() returns once the row is
inserted, so a request never waits on SMTP, and a failed send is retried with
backoff.
EmailModule exports EmailService and EmailStatsService.
SMTP providers
For local development the template ships MailDev:
cd backend
npm run dev:email # SMTP on :1025, web UI on http://localhost:1080
The backend defaults (localhost:1025, no auth) already point at it, so local email testing needs no env vars. Mailtrap and Mailhog work the same way.
For production, any standards-compliant SMTP provider works. Verify your sending domain (SPF and DKIM) before sending to real addresses.
Related
- Auth Flow - how magic-link sign-in works
- Environment Variables - full SMTP config reference
- Architecture - worker claim and recovery mechanics