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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tresdoce-nestjs-toolkit/mailer

v2.0.12

Published

Tresdoce NestJS Toolkit - Módulo para envíos de mail

Readme

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/mailer
yarn add @tresdoce-nestjs-toolkit/mailer

📦 Dependencias internas

Este paquete no tiene dependencias internas del toolkit. Puede utilizarse de forma independiente.

⚙️ Configuración

Agregar los datos de conexión SMTP en configuration.ts utilizando el key mailer que contenga los datos desde las variables de entorno.

//./src/config/configuration.ts
import { Typings } from '@tresdoce-nestjs-toolkit/core';
import { registerAs } from '@nestjs/config';
import { join } from 'path';
import { HandlebarsAdapter } from '@tresdoce-nestjs-toolkit/mailer';

export default registerAs('config', (): Typings.AppConfig => {
  return {
    //...
    mailer: {
      transport: {
        host: process.env.EMAIL_HOST,
        port: parseInt(process.env.EMAIL_PORT, 10) || 587,
        secure: true,
        requireTLS: true,
        auth: {
          user: process.env.EMAIL_USER,
          pass: process.env.EMAIL_PASSWORD,
        },
      },
      defaults: {
        from: process.env.EMAIL_USER,
      },
      // Opcional: configuración de templates
      template: {
        dir: join(__dirname, './templates'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    },
    //...
  };
});

transport: Configuración del transporte SMTP. Puede ser un objeto de opciones, una cadena de conexión URL (smtps://[email protected]:[email protected]) o una instancia de transporte nodemailer.

  • Type: SMTPTransport.Options | string | Transport
  • Required: true (a menos que se use transports)

transport.host: Servidor SMTP.

  • Type: String

transport.port: Puerto SMTP.

  • Type: Number
  • Default: 587

transport.secure: Utilizar TLS.

  • Type: Boolean
  • Default: true

transport.requireTLS: Exige TLS aunque secure sea false.

  • Type: Boolean
  • Default: true

Nota: Las constantes defaultTransportOptions exportadas por el módulo tienen preconfigurado { secure: true, requireTLS: true }.

transport.auth.user: Usuario SMTP.

  • Type: String

transport.auth.pass: Contraseña SMTP.

  • Type: String

transports: Permite configurar múltiples transportadores con nombre para usar en entornos multi-tenant o multi-cuenta.

  • Type: { [name: string]: SMTPTransport | SMTPTransport.Options | string }
  • Required: false

defaults: Opciones por defecto aplicadas a todos los correos enviados.

template.dir: Directorio donde se encuentran los templates de email.

  • Type: String

template.adapter: Adaptador de template a usar (HandlebarsAdapter, EjsAdapter o PugAdapter).

  • Type: TemplateAdapter

template.options: Opciones adicionales pasadas al adaptador de template (ej. { strict: true } para Handlebars).

  • Type: Object

options.partials.dir: Directorio de partials de Handlebars (sólo aplica con HandlebarsAdapter).

  • Type: String

👨‍💻 Uso

Importación del módulo (configuración centralizada)

Importar el MailerModule en el archivo app.module.ts. El módulo obtiene la configuración automáticamente desde ConfigService (key config.mailer).

//./src/app.module.ts
import { MailerModule } from '@tresdoce-nestjs-toolkit/mailer';

@Module({
  //...
  imports: [
    //...
    MailerModule,
    //...
  ],
  //...
})
export class AppModule {}

Importación estática con forRoot

Cuando no se usa la configuración centralizada, se puede inicializar el módulo directamente con forRoot:

//./src/app.module.ts
import { MailerModule } from '@tresdoce-nestjs-toolkit/mailer';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: 'smtps://[email protected]:[email protected]',
      defaults: {
        from: '"App" <[email protected]>',
      },
    }),
  ],
})
export class AppModule {}

Envío de email simple

Inyectar el MailerService para realizar el envío de mails.

//./src/app.service.ts
import { Injectable } from '@nestjs/common';
import { MailerService } from '@tresdoce-nestjs-toolkit/mailer';

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

  async sendMail() {
    try {
      return await this.mailerService.sendMail({
        to: 'destinatario <[email protected]>',
        from: 'remitente <[email protected]>',
        subject: 'Asunto del mail',
        text: 'Cuerpo en texto plano',
        html: '<b>Cuerpo en HTML</b>',
      });
    } catch (error) {
      throw new Error(error.message);
    }
  }
}

Templates de email

Se pueden usar tres adaptadores de template: Handlebars, EJS y Pug.

Handlebars

//./src/config/configuration.ts
import { join } from 'path';
import { HandlebarsAdapter } from '@tresdoce-nestjs-toolkit/mailer';

mailer: {
  transport: { /* ... */ },
  template: {
    dir: join(__dirname, './templates'),
    adapter: new HandlebarsAdapter(),
    options: {
      strict: true,
    },
  },
  // Soporte de partials: directorio con archivos *.hbs registrados automáticamente
  options: {
    partials: {
      dir: join(__dirname, './templates/partials'),
    },
  },
}

Template Handlebars (templates/welcome.hbs):

<p>Hola {{name}},</p>
<p>Bienvenido a NestJS Mailer.</p>
await this.mailerService.sendMail({
  to: email,
  subject: 'Bienvenido',
  template: './welcome',
  context: { name: 'Juan' },
});

EJS

//./src/config/configuration.ts
import { join } from 'path';
import { EjsAdapter } from '@tresdoce-nestjs-toolkit/mailer';

mailer: {
  transport: { /* ... */ },
  template: {
    dir: join(__dirname, './templates'),
    adapter: new EjsAdapter(),
  },
}

Template EJS (templates/welcome.ejs):

<p>Hola <%= name %>,</p>
<p>Bienvenido a NestJS Mailer.</p>
await this.mailerService.sendMail({
  to: email,
  subject: 'Bienvenido',
  template: './welcome',
  context: { name: 'Juan' },
});

Pug

//./src/config/configuration.ts
import { join } from 'path';
import { PugAdapter } from '@tresdoce-nestjs-toolkit/mailer';

mailer: {
  transport: { /* ... */ },
  template: {
    dir: join(__dirname, './templates'),
    adapter: new PugAdapter(),
  },
}

Template Pug (templates/welcome.pug):

p Hola #{name},
p Bienvenido a NestJS Mailer.
await this.mailerService.sendMail({
  to: email,
  subject: 'Bienvenido',
  template: './welcome',
  context: { name: 'Juan' },
});

CSS Inline

Todos los adaptadores tienen el inlining de CSS habilitado por defecto (inlineCssEnabled: true). Para deshabilitar o personalizar:

new HandlebarsAdapter(undefined, {
  inlineCssEnabled: false,
});

// O con opciones de @css-inline/css-inline:
new EjsAdapter({
  inlineCssEnabled: true,
  inlineCssOptions: {
    /* opciones de css-inline */
  },
});

Múltiples transportadores

Cuando se necesita enviar correos desde distintas cuentas, se puede configurar transports:

mailer: {
  transports: {
    primary: {
      host: process.env.EMAIL_HOST_PRIMARY,
      port: 587,
      auth: { user: process.env.EMAIL_USER_PRIMARY, pass: process.env.EMAIL_PASS_PRIMARY },
    },
    secondary: 'smtps://[email protected]:[email protected]',
  },
  defaults: { from: '"App" <[email protected]>' },
}

Para enrutar el envío a un transportador específico, se usa el campo transporterName:

await this.mailerService.sendMail({
  to: '[email protected]',
  subject: 'Asunto',
  text: 'Mensaje',
  transporterName: 'secondary', // nombre de la clave en transports
});

📖 API Reference

MailerModule

| Método | Descripción | | ----------------------------------------------- | --------------------------------------------------------------------------------------------- | | MailerModule (sin argumentos) | Carga la configuración desde ConfigService (key config.mailer). Decorado con @Global(). | | MailerModule.forRoot(options?: MailerOptions) | Inicialización estática con opciones directas. |

MailerService

| Método | Descripción | | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | sendMail(options: ISendMailOptions): Promise<SentMessageInfo> | Envía un email. Si options.transporterName está definido, usa ese transportador; de lo contrario usa el transportador único. |

ISendMailOptions

| Campo | Tipo | Descripción | | ----------------- | ------------------------------------------ | --------------------------------------------------------------- | | to | EmailAddress | Destinatario(s) | | cc | EmailAddress | Copia(s) | | bcc | EmailAddress | Copia(s) oculta(s) | | from | string \| Address | Remitente | | replyTo | string \| Address | Dirección de respuesta | | inReplyTo | string \| Address | En respuesta a | | subject | string | Asunto | | text | string \| Buffer \| AttachmentLikeObject | Cuerpo en texto plano | | html | string \| Buffer | Cuerpo en HTML | | sender | string \| Address | Remitente físico (Sender header) | | raw | string \| Buffer | Mensaje raw RFC822 | | textEncoding | 'quoted-printable' \| 'base64' | Codificación del texto | | references | string \| string[] | Referencias de mensajes anteriores | | encoding | string | Codificación del mensaje | | date | Date \| string | Fecha del mensaje | | headers | Headers | Headers adicionales | | attachments | Attachment[] | Archivos adjuntos | | dkim | DKIM.Options | Opciones de firma DKIM | | template | string | Nombre del template a renderizar | | context | { [name: string]: any } | Variables de contexto para el template | | transporterName | string | Nombre del transportador (para configuración multi-transporter) |

MailerOptions

| Campo | Tipo | Descripción | | ---------------------- | ---------------------------------------------------------------------- | ------------------------------------------ | | transport | TransportType | Configuración del transporte único | | transports | { [name: string]: SMTPTransport \| SMTPTransport.Options \| string } | Múltiples transportadores nombrados | | defaults | Options | Opciones por defecto para todos los envíos | | template.dir | string | Directorio de templates | | template.adapter | TemplateAdapter | Adaptador de template | | template.options | object | Opciones adicionales del adaptador | | options.partials.dir | string | Directorio de partials Handlebars |

TemplateAdapterConfig

| Campo | Tipo | Default | Descripción | | ------------------ | --------- | ------- | -------------------------------------- | | inlineCssEnabled | boolean | true | Habilita el inlining de CSS en el HTML | | inlineCssOptions | Options | {} | Opciones de @css-inline/css-inline |

Adaptadores exportados

| Clase | Peer dep requerida | Constructor | | ------------------- | ----------------------- | ------------------------------------------ | | HandlebarsAdapter | handlebars (incluida) | new HandlebarsAdapter(helpers?, config?) | | EjsAdapter | ejs (incluida) | new EjsAdapter(config?) | | PugAdapter | pug (incluida) | new PugAdapter(config?) |

Constantes exportadas

| Constante | Valor | Descripción | | -------------------------- | ------------------------------------ | ---------------------------------- | | MAILER_OPTIONS | 'MAILER_OPTIONS' | Token de inyección de opciones | | MAILER_TRANSPORT_FACTORY | 'MAILER_TRANSPORT_FACTORY' | Token de la factory de transporte | | defaultTransportOptions | { secure: true, requireTLS: true } | Opciones de transporte por defecto |

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.