npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@c1x/nest-mailer

v1.0.6

Published

A flexible and easy-to-use mailer module for NestJS applications, supporting multiple email providers including SMTP, AWS SES, and SendGrid.

Readme

@c1x/nest-mailer

A flexible and easy-to-use mailer module for NestJS applications, supporting multiple email providers including SMTP, AWS SES, and SendGrid.

Features

  • 📧 Multiple provider support (SMTP, AWS SES, SendGrid)
  • ⚙️ Environment-based configuration
  • 🚀 Asynchronous module configuration
  • 📎 Attachment support
  • 🎨 HTML email support
  • 💪 Type-safe implementation
  • 🔍 Detailed error logging

Installation

npm install @c1x/nest-mailer

Quick Start

  1. Import the MailerModule in your app.module.ts:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MailerModule } from '@c1x/nest-mailer';
import { join } from 'path';

@Module({
  imports: [
    ConfigModule.forRoot(),
    MailerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        // Required: Provider configuration
        provider: configService.get('MAIL_PROVIDER', 'sendgrid'),
        credentials: {
          apiKey: configService.get('SENDGRID_API_KEY'),
        },
        // Optional: Template configuration
        templatesDir: join(__dirname, 'templates'), // Only needed if using templates
      }),
    }),
  ],
})
export class AppModule {}
  1. Configure your environment variables:
# Choose your preferred provider and configure accordingly

# SendGrid Configuration
SENDGRID_API_KEY=your_api_key
MAIL_FROM_NAME=Your App Name
[email protected]

# Or SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
[email protected]
SMTP_PASS=your-app-password

# Or AWS SES Configuration
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_REGION=your_region
  1. Use the MailerService in your application:
import { Injectable } from '@nestjs/common';
import { MailerService } from '@c1x/nest-mailer';

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWelcomeEmail(userEmail: string) {
    await this.mailerService.sendMail({
      to: userEmail,
      fromName: 'Your App Name',    // New: Separate sender name
      fromAddress: '[email protected]',  // New: Separate sender email
      subject: 'Welcome to Our App!',
      text: 'Welcome to our application...',
      html: '<h1>Welcome!</h1><p>We're glad to have you on board.</p>',
    });
  }
}

Provider Configuration

SendGrid Configuration

MailerModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (configService: ConfigService) => ({
    provider: 'sendgrid',
    credentials: {
      apiKey: configService.get('SENDGRID_API_KEY'),
    },
    // Optional template support
    templatesDir: join(__dirname, 'templates'),
  }),
}),

SMTP Configuration

MailerModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (configService: ConfigService) => ({
    provider: 'smtp',
    credentials: {
      host: configService.get('SMTP_HOST'),
      port: parseInt(configService.get('SMTP_PORT')),
      secure: configService.get('SMTP_SECURE') === 'true',
      auth: {
        user: configService.get('SMTP_USER'),
        pass: configService.get('SMTP_PASS'),
      },
    },
  }),
}),

AWS SES Configuration

MailerModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (configService: ConfigService) => ({
    provider: 'aws-ses',
    credentials: {
      accessKeyId: configService.get('AWS_ACCESS_KEY_ID'),
      secretAccessKey: configService.get('AWS_SECRET_ACCESS_KEY'),
      region: configService.get('AWS_REGION'),
    },
  }),
}),

API Reference

MailOptions Interface

interface MailOptions {
  // Required fields
  to: string | string[];
  fromName: string;      // New: Sender name field
  fromAddress: string;   // New: Sender email field
  subject: string;

  // Optional fields
  text?: string;         // Plain text content
  html?: string;         // HTML content
  template?: string;     // Template name (if using templates)
  context?: any;         // Template variables (if using templates) example context variables {'name':'json','email':'[email protected]'}
  attachments?: Array<{
    filename: string;
    content: Buffer | string;
    contentType?: string;
    cid?: string;        // For inline images
  }>;
}

Provider Configurations

interface SmtpConfig {
  host: string;
  port: number;
  secure: boolean;
  auth: {
    user: string;
    pass: string;
  };
}

interface AwsSesConfig {
  accessKeyId: string;
  secretAccessKey: string;
  region: string;
}

interface SendGridConfig {
  apiKey: string;
}

Error Handling

The module includes built-in error handling. Here's an example of how to handle errors:

try {
  await this.mailerService.sendMail({
    to: '[email protected]',
    from: '[email protected]',
    subject: 'Test Email',
    text: 'This is a test email',
  });
} catch (error) {
  // Handle specific error types
  if (error.code === 'EAUTH') {
    // Handle authentication error
  } else if (error.code === 'ETIMEDOUT') {
    // Handle timeout error
  }
  throw error;
}

Sending Emails with Attachments

Here are different examples of sending emails with attachments:

  1. Send with Buffer attachment:
import { Injectable } from '@nestjs/common';
import { MailerService } from '@c1x/nest-mailer';
import * as fs from 'fs';

@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWithAttachment() {
    // Read file as buffer
    const fileBuffer = fs.readFileSync('path/to/file.pdf');

    await this.mailerService.sendMail({
      to: '[email protected]',
      fromAddress: '[email protected]',
      fromName:"test",
      subject: 'Document Attached',
      text: 'Please find the attached document.',
      attachments: [
        {
          filename: 'document.pdf',
          content: fileBuffer,
          contentType: 'application/pdf',
        }
      ]
    });
  }
}
  1. Send with multiple attachments:
@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWithMultipleAttachments() {
    await this.mailerService.sendMail({
      to: '[email protected]',
      fromAddress: '[email protected]',
      fromName:"test",
      subject: 'Multiple Attachments',
      text: 'Please find the attached files.',
      attachments: [
        {
          filename: 'report.pdf',
          content: fs.readFileSync('path/to/report.pdf'),
          contentType: 'application/pdf',
        },
        {
          filename: 'image.jpg',
          content: fs.readFileSync('path/to/image.jpg'),
          contentType: 'image/jpeg',
        },
        {
          filename: 'data.csv',
          content: fs.readFileSync('path/to/data.csv'),
          contentType: 'text/csv',
        }
      ]
    });
  }
}
  1. Inline images in HTML email:
@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWithInlineImages() {
    await this.mailerService.sendMail({
      to: '[email protected]',
      fromAddress: '[email protected]',
      fromName:"test",
      subject: 'Email with Inline Image',
      html: `
        <h1>Welcome!</h1>
        <p>Here's our logo:</p>
        <img src="cid:unique-logo-id" />
      `,
      attachments: [
        {
          filename: 'logo.png',
          content: fs.readFileSync('path/to/logo.png'),
          contentType: 'image/png',
          cid: 'unique-logo-id' // Content ID for referencing in HTML
        }
      ]
    });
  }
}
  1. Send with Base64 attachment:
@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWithBase64Attachment() {
    const base64Content = 'base64_encoded_string';

    await this.mailerService.sendMail({
      to: '[email protected]',
      fromAddress: '[email protected]',
      fromName:"test",
      subject: 'Image Attached',
      html: '<h1>Check out this image!</h1>',
      attachments: [
        {
          filename: 'image.png',
          content: base64Content,
          contentType: 'image/png',
        }
      ]
    });
  }
}
  1. Use the MailerService with templates in your application:
import { Injectable } from '@nestjs/common';
import { MailerService } from '@c1x/nest-mailer';

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendWelcomeEmail(userEmail: string, userName: string) {
    await this.mailerService.sendMail({
      to: userEmail,
      fromAddress: '[email protected]',
      fromName:"test",
      subject: 'Welcome to Our App!',
      template: 'welcome',  // References welcome.hbs
      context: {
        appName: 'YourApp',
        userName: userName,
        welcomeMessage: 'We\'re excited to have you on board!'
      }
    });
  }
}

Best Practices

  1. Always use environment variables for sensitive credentials
  2. Implement proper error handling
  3. Use type-safe interfaces provided by the library
  4. Consider implementing a retry mechanism for failed emails
  5. Use HTML templates for consistent email styling

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT

Support

For issues and feature requests, please create an issue in the GitHub repository.