๐ NestJS Mailable
Advanced mailable classes for NestJS with fluent API, multiple transports, and comprehensive template support
โจ Features
- ๐ฏ Advanced Mailable Classes - Organized, reusable email components
- ๐ Fluent API - Clean, chainable interface for sending emails
- ๐ง Multiple Transports - SMTP, Amazon SES, Mailgun support
- ๐จ Template Engines - Handlebars, EJS, Pug with auto-detection
- ๐ Attachment Builder - Flexible file attachment handling
- โ๏ธ Easy Configuration - Simple setup with TypeScript support
- ๐งช Testing Ready - Built-in testing utilities
๐ฆ Installation
Basic Installation
npm install nestjs-mailable nodemailer handlebars
Choose Your Transport & Template Engine
SMTP Transport
npm install nestjs-mailable nodemailer handlebars
npm install nestjs-mailable nodemailer ejs
npm install nestjs-mailable nodemailer pug
Amazon SES Transport
npm install nestjs-mailable aws-sdk handlebars
npm install nestjs-mailable aws-sdk ejs
npm install nestjs-mailable aws-sdk pug
Mailgun Transport
npm install nestjs-mailable mailgun.js handlebars
npm install nestjs-mailable mailgun.js ejs
npm install nestjs-mailable mailgun.js pug
All-in-One Installation
npm install nestjs-mailable nodemailer aws-sdk mailgun.js handlebars ejs pug
๐ Quick Start
1. Module Setup
import { Module } from '@nestjs/common';
import { MailModule, TransportType, TEMPLATE_ENGINE } from 'nestjs-mailable';
@Module({
imports: [
MailModule.forRoot({
transport: {
type: TransportType.SMTP,
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'your-email@gmail.com',
pass: 'your-password',
},
},
from: {
address: 'noreply@yourapp.com',
name: 'Your App'
},
templates: {
engine: TEMPLATE_ENGINE.HANDLEBARS,
directory: './templates',
},
}),
],
})
export class AppModule {}
2. Simple Email Sending
import { Injectable } from '@nestjs/common';
import { MailService } from 'nestjs-mailable';
@Injectable()
export class NotificationService {
constructor(private mailService: MailService) {}
async sendWelcomeEmail(user: { name: string; email: string }) {
await this.mailService
.to(user.email)
.subject('Welcome!')
.template('welcome', { name: user.name })
.send();
}
}
๐ง Mailable Classes
Simple Mailable
import { Mailable, Content } from 'nestjs-mailable';
export class WelcomeMail extends Mailable {
constructor(private user: { name: string; email: string }) {
super();
}
async build(): Promise<Content> {
return {
subject: `Welcome ${this.user.name}!`,
template: 'welcome',
context: { name: this.user.name }
};
}
}
await this.mailService
.to(user.email)
.send(new WelcomeMail(user));
Advanced Mailable
import {
MailableClass as Mailable,
AttachmentBuilder,
MailableEnvelope,
MailableContent,
MailableAttachment
} from 'nestjs-mailable';
export class OrderShippedMail extends Mailable {
constructor(private order: Order) {
super();
}
envelope(): MailableEnvelope {
return {
subject: `Order #${this.order.id} has shipped!`,
tags: ['order', 'shipment'],
metadata: { orderId: this.order.id }
};
}
content(): MailableContent {
return {
template: 'orders/shipped',
with: {
customerName: this.order.customerName,
orderNumber: this.order.id,
trackingUrl: this.order.trackingUrl
}
};
}
attachments(): MailableAttachment[] {
return [
AttachmentBuilder
.fromPath('./invoices/invoice.pdf')
.as('Invoice.pdf')
.build()
];
}
}
await this.mailService
.to(order.customerEmail)
.cc('sales@company.com')
.send(new OrderShippedMail(order));
๐ง Configuration Examples
Environment-based Configuration
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot(),
MailModule.forRootAsync({
imports: [ConfigModule],
useFactory: (config: ConfigService) => ({
transport: {
type: TransportType.SMTP,
host: config.get('MAIL_HOST'),
port: config.get('MAIL_PORT', 587),
auth: {
user: config.get('MAIL_USER'),
pass: config.get('MAIL_PASS'),
},
},
from: {
address: config.get('MAIL_FROM_ADDRESS'),
name: config.get('MAIL_FROM_NAME'),
},
templates: {
engine: TEMPLATE_ENGINE.HANDLEBARS,
directory: './templates',
},
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}
Amazon SES Configuration
MailModule.forRoot({
transport: {
type: TransportType.SES,
region: 'us-east-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
},
from: { address: 'noreply@yourapp.com', name: 'Your App' },
templates: {
engine: TEMPLATE_ENGINE.HANDLEBARS,
directory: './templates',
},
})
Handlebars with Custom Helpers
MailModule.forRoot({
templates: {
engine: TEMPLATE_ENGINE.HANDLEBARS,
directory: './templates',
options: {
helpers: {
currency: (amount: number) => `$${amount.toFixed(2)}`,
formatDate: (date: Date) => date.toLocaleDateString(),
uppercase: (str: string) => str.toUpperCase(),
},
},
partials: {
header: './templates/partials/header',
footer: './templates/partials/footer',
},
},
})
๐งช Development & Testing
Mock Servers for Development
For development and testing, you can use mock servers that simulate the email service APIs:
SMTP Mock Server
node mock-ses-server.js
SES Mock Server
node examples/ses-mock-server.js
Mailgun Mock Server
npm install express cors multer fs-extra
node mailgun-mock-server.js
Docker Compose for Mock Servers
Start all mock servers with Docker:
docker-compose -f docker-compose.mock.yml up
docker-compose -f docker-compose.mock.yml up mailgun-mock
docker-compose -f docker-compose.mock.yml up ses-mock
Mock Server Configuration
Configure your application to use mock servers:
MAIL_TRANSPORT=mailgun
MAILGUN_DOMAIN=test-domain.com
MAILGUN_API_KEY=test-api-key
MAILGUN_HOST=localhost:3001
MAILGUN_PROTOCOL=http:
MAIL_TRANSPORT=ses
SES_ENDPOINT=http:
SES_REGION=us-east-1
SES_ACCESS_KEY_ID=test
SES_SECRET_ACCESS_KEY=test
Testing Emails
Mock servers provide endpoints to inspect sent emails:
curl http://localhost:3001/emails
curl http://localhost:4566/emails
curl http://localhost:3001/emails/EMAIL_ID
๐ Documentation
๐ Full Documentation - Comprehensive guides, API reference, and examples
๐ Supported Transports
SMTP | Standard SMTP servers | โ
|
Amazon SES | AWS Simple Email Service | โ
|
Mailgun | Mailgun API | โ
|
๐จ Template Engines
Handlebars | .hbs | โ
| โ
|
EJS | .ejs | โ ๏ธ | โ
|
Pug | .pug | โ ๏ธ | โ
|
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
๐ License
MIT ยฉ NestJS Mailable
Built with โค๏ธ for the NestJS community