Módulo Email

Envio de e-mails

Mailer NestJS + Nodemailer/SMTP, templates Pug e endpoint REST autenticado com HTML inline.

Visão geral

O módulo email encapsula @nestjs-modules/mailer com adapter Pug. Em desenvolvimento, use MailHog (Docker). Use sendMail com html inline ou template + context; há também POST /email/send.

Pontos principais

  • • Transport SMTP via ConfigService (smtp.*)
  • • EmailService exportado para outros módulos
  • • Templates Pug em modules/email/templates
  • • sendMail permite html inline (template é ignorado quando html está presente)
  • • REST protegido com JWT — sem @Roles

Estrutura

Filesystemsrc/modules/email
src/modules/email/
├── email.module.ts
├── email.controller.ts
├── email.service.ts
├── dtos/
│   └── send-email.dto.ts
└── templates/
    ├── layout.pug
    └── *.pug

src/config/smtp.config.ts

Templates Pug

Coloque arquivos .pug em templates/. O nome do arquivo (sem extensão) é o valor de template. Use layout.pug com extends para HTML compartilhado.

  • • layout.pug — estrutura HTML base (opcional, via extends)
  • • template: 'welcome' → templates/welcome.pug
  • • context — objeto com variáveis disponíveis no Pug
TypeScripttemplate + context
await this.emailService.sendMail({
  to: '[email protected]',
  subject: 'Welcome',
  template: 'welcome',
  context: { name: 'Alice' },
});

Configuração SMTP

Namespace smtp em src/config/smtp.config.ts. Variáveis no .env:

Environment.env
SMTP_HOST=localhost
SMTP_PORT=587
SMTP_SECURE=false
SMTP_REQUIRE_TLS=false
SMTP_USER=
SMTP_PASSWORD=
[email protected]

Docker / MailHog

No Compose, o app aponta para MailHog (SMTP 1025). Abra /mailhog/ para ver os e-mails.

EmailService

Métodos públicos do service:

  • • sendMail(options) — pass-through; use html para inline ou template + context
  • • sendEmailConfirmation(email, token) — helper do Auth (template email-confirmation)
  • • sendPasswordReset(email, token) — helper do Auth (template password-reset)

API REST

JWT obrigatório. Qualquer usuário autenticado pode chamar (sem @Roles).

Enviar e-mail genérico (HTML inline)

Body: to (e-mail), subject, html. O controller usa sendMail com html — sem template.

HTTP RequestPOST
POST /api/v1/email/send
Content-Type: application/json
Authorization: Bearer <access_token>

{
  "to": "[email protected]",
  "subject": "Test Email",
  "html": "

Hello

This is a test email

" }

Resposta

HTTP Response200
{
  "message": "Email sent successfully"
}

Integração com Auth

AuthModule importa EmailModule e usa helpers com templates próprios (email-confirmation, password-reset):

  • • POST /auth/register → sendEmailConfirmation
  • • POST /auth/resend-verification → sendEmailConfirmation
  • • POST /auth/forgot-password → sendPasswordReset
Ver documentação Auth & JWT

Usar em outro módulo

Importe EmailModule e injete EmailService. Inline ou template:

TypeScriptFeature module
@Module({
  imports: [EmailModule],
  providers: [MyService],
})
export class MyModule {}

@Injectable()
export class MyService {
  constructor(private readonly emailService: EmailService) {}

  // HTML inline (adapter de template ignorado)
  async notifyInline(email: string) {
    await this.emailService.sendMail({
      to: email,
      subject: 'Hello',
      html: '

Hi

', }); } // Template Pug async notifyTemplate(email: string, name: string) { await this.emailService.sendMail({ to: email, subject: 'Welcome', template: 'welcome', context: { name }, }); } }

Atenção

Desenvolvimento

Com MailHog, SMTP_SECURE e SMTP_REQUIRE_TLS devem ser false; auth pode ficar vazia.

Produção

Use um provedor SMTP real (SendGrid, SES, etc.) e credenciais fortes. Nunca commite senhas. Os .pug são copiados para dist via nest-cli assets.

Explorar