HazelJS Mail Package
@hazeljs/mail provides structured, provider-agnostic email for HazelJS — an EmailDocument compose model, delivery policy, multi-provider send (SMTP / SES / Resend / SendGrid / Mailgun), typed mailables, and lifecycle webhooks.
Quick Reference
- Purpose: First-class email domain model (compose → policy → render → provider), not just a Nodemailer wrapper.
- When to use: Transactional and lifecycle email with brand themes, staging intercept, suppress lists, and bounce/complaint webhooks.
- Key concepts:
MailModule,MailService,email()compose API,EmailDocument,MailProvider, delivery policy, mailables,/mail/webhook/:provider. - Dependencies:
@hazeljs/core; optional peers:nodemailer,handlebars,mjml,@hazeljs/queue,@hazeljs/event-emitter. - Common patterns:
MailModule.forRoot({ memory: true })locally → swapses/sendgrid/mailgun/resend/smtpin production;email().section().cta().build()thenmail.send(doc). - Common mistakes: Sending marketing mail without unsubscribe headers; skipping staging intercept; coupling app code to a single provider SDK.
Purpose
Most mail libraries stop at sendMail({ to, html }). Nest-style modules add transports and templates, but still treat email as a bag of transport options. @hazeljs/mail goes further:
- EmailDocument AST + Compose API — layouts, sections, CTAs, ICS calendar parts, List-Unsubscribe, tags, and brand themes as structured TypeScript.
- Delivery policy — categories (
transactional|marketing|security), suppress, intercept, quiet hours, rate limits. - Provider facade — same send path for memory/log (dev), SMTP, SES (SigV4 fetch), Resend, SendGrid, Mailgun, or custom
MailProviders with failover + retry. - Lifecycle webhooks — normalize bounce / complaint / delivery / open / click and emit
mail.*events. - Typed mailables — Zod-validated catalogs for discoverable, testable emails.
Architecture
flowchart TB App[App / Mailables] Compose[Compose API] Doc[EmailDocument] Policy[DeliveryPolicy] MailSvc[MailService] Providers[Provider registry] Webhooks[MailController] App --> Compose Compose --> Doc Doc --> MailSvc MailSvc --> Policy Policy --> Providers Webhooks --> MailSvc
Quick start
import { HazelModule } from '@hazeljs/core';
import { MailModule, email } from '@hazeljs/mail';
@HazelModule({
imports: [
MailModule.forRoot({
memory: true,
defaults: { from: 'Hazel <noreply@hazeljs.ai>' },
brand: { name: 'Hazel', colors: { primary: '#0F766E' } },
policy: {
intercept: {
enabled: process.env.NODE_ENV !== 'production',
to: 'qa@example.com',
},
},
}),
],
})
export class AppModule {}
const doc = email()
.category('transactional')
.subject(`Welcome, ${user.name}`)
.to(user.email)
.section({ heading: 'Welcome', body: 'Glad you are here.' })
.cta({ label: 'Open dashboard', href })
.unsubscribe({ url: unsubUrl })
.build();
await mailService.send(doc);
Providers
MailModule.forRoot({
defaultProvider: 'ses',
failover: ['sendgrid', 'mailgun', 'resend'],
ses: { region: 'eu-west-1' },
sendgrid: { apiKey: process.env.SENDGRID_API_KEY! },
mailgun: {
apiKey: process.env.MAILGUN_API_KEY!,
domain: 'mg.example.com',
region: 'eu',
},
resend: { apiKey: process.env.RESEND_API_KEY! },
smtp: { host: 'smtp.example.com', port: 587, auth: { user, pass } },
});
| Provider | Notes |
|---|---|
memory | Assertable mailbox for tests |
log | Console preview in development |
smtp | Requires nodemailer peer |
ses | SigV4 HTTP API, no AWS SDK required |
resend | HTTP API + webhook signature verify |
sendgrid | v3 Mail Send API; EU via baseUrl: 'https://api.eu.sendgrid.com' |
mailgun | Messages API; region: 'eu' or custom baseUrl |
Mailables & templates
import { z } from 'zod';
import { defineMailable, globalMailCatalog } from '@hazeljs/mail';
const WelcomeMail = defineMailable({
name: 'welcome',
schema: z.object({ name: z.string() }),
build: (data, { email }) =>
email()
.subject(`Welcome, ${data.name}`)
.to('placeholder@example.com')
.section({ body: `Hi ${data.name}` })
.build(),
});
globalMailCatalog.register(WelcomeMail);
await mail.sendMailable(WelcomeMail, { to: user.email, data: { name: user.name } });
File templates (optional Handlebars peer):
MailModule.forRoot({
template: { dir: './emails', engine: 'handlebars' },
ses: { region: 'us-east-1' },
});
await mail.sendTemplate('welcome', { to: user.email, context: { name: user.name } });
Webhooks & events
POST /mail/webhook/:provider — raw body preferred for signature verification.
Outbound events: mail.sent, mail.failed, mail.suppressed, mail.intercepted, mail.queued, mail.deferred.
Inbound: mail.bounced, mail.complained, mail.delivered, mail.opened, mail.clicked.
Queue
MailModule.forRoot({
memory: true,
queue: { enabled: true, name: 'mail' },
queueClient: queueService,
});
await mail.sendLater(doc);
Related packages
@hazeljs/queue— backgroundsendLater@hazeljs/event-emitter—mail.*events@hazeljs/payment— similar multi-provider + webhook pattern