Socket
Book a DemoInstallSign in
Socket

nestjs-mailable

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-mailable

A comprehensive NestJS mail package with design patterns for email handling, templating, and multi-provider support

1.4.0
latest
Source
npmnpm
Version published
Weekly downloads
100
-42.53%
Maintainers
1
Weekly downloads
ย 
Created
Source

๐Ÿš€ NestJS Mailable

Advanced mailable classes for NestJS with fluent API, multiple transports, and comprehensive template support

NPM version License Downloads Build Status Documentation

โœจ 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

# With Handlebars (recommended)
npm install nestjs-mailable nodemailer handlebars

# With EJS
npm install nestjs-mailable nodemailer ejs

# With Pug
npm install nestjs-mailable nodemailer pug

Amazon SES Transport

# With Handlebars
npm install nestjs-mailable aws-sdk handlebars

# With EJS
npm install nestjs-mailable aws-sdk ejs

# With Pug
npm install nestjs-mailable aws-sdk pug

Mailgun Transport

# With Handlebars
npm install nestjs-mailable mailgun.js handlebars

# With EJS
npm install nestjs-mailable mailgun.js ejs

# With Pug
npm install nestjs-mailable mailgun.js pug

All-in-One Installation

# Install with all transports and template engines
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 }
    };
  }
}

// Usage
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()
    ];
  }
}

// Usage
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({
  // ... transport config
  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

# Start SMTP mock server (port 1025)
node mock-ses-server.js

SES Mock Server

# Start SES mock server (port 4566)
node examples/ses-mock-server.js

Mailgun Mock Server

# Install dependencies
npm install express cors multer fs-extra

# Start Mailgun mock server (port 3001)
node mailgun-mock-server.js

Docker Compose for Mock Servers

Start all mock servers with Docker:

# Start all mock servers
docker-compose -f docker-compose.mock.yml up

# Or start specific services
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:

// .env for Mailgun mock
MAIL_TRANSPORT=mailgun
MAILGUN_DOMAIN=test-domain.com
MAILGUN_API_KEY=test-api-key
MAILGUN_HOST=localhost:3001
MAILGUN_PROTOCOL=http:

// .env for SES mock
MAIL_TRANSPORT=ses
SES_ENDPOINT=http://localhost:4566
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:

# List emails sent via Mailgun mock
curl http://localhost:3001/emails

# List emails sent via SES mock
curl http://localhost:4566/emails

# Get specific email details
curl http://localhost:3001/emails/EMAIL_ID

๐Ÿ“š Documentation

๐Ÿ“– Full Documentation - Comprehensive guides, API reference, and examples

๐Ÿ›  Supported Transports

TransportDescriptionStatus
SMTPStandard SMTP serversโœ…
Amazon SESAWS Simple Email Serviceโœ…
MailgunMailgun APIโœ…

๐ŸŽจ Template Engines

EngineExtensionHelper SupportPartials
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

Keywords

nestjs

FAQs

Package last updated on 31 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with โšก๏ธ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.