Guide · JavaScript & TypeScript
How to send email with NestJS
Wrap the Stack Emails API in an injectable NestJS service so any module can send transactional email with one method call.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import { Injectable, InternalServerErrorException } from "@nestjs/common";
type Email = { to: string | string[]; subject: string; html?: string; text?: string };
@Injectable()
export class MailService {
private readonly from = "Acme <hello@mail.acme.com>";
async send(email: Email) {
const res = await fetch("https://stackemails.com/v1/emails", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.STACKEMAILS_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ from: this.from, ...email }),
});
const data = await res.json();
if (!res.ok) throw new InternalServerErrorException(data.error?.message ?? "Email failed");
return data as { id: string; status: string };
}
}
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
Register MailService in a MailModule, export it, and inject it where you need it:
constructor(private readonly mail: MailService) {}
await this.mail.send({ to: user.email, subject: "Verify your email", html: verifyHtml });
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.