template-saas/docs/01-modulos/SAAS-013-email.md
rckrdmrd 50a821a415
Some checks failed
CI / Backend CI (push) Has been cancelled
CI / Frontend CI (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / CI Summary (push) Has been cancelled
[SIMCO-V38] feat: Actualizar a SIMCO v3.8.0
- HERENCIA-SIMCO.md actualizado con directivas v3.7 y v3.8
- Actualizaciones de configuracion

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 08:53:08 -06:00

6.3 KiB

id title type status priority module version created_date updated_date
SAAS-013 Email Module Module Published P1 email 1.0.0 2026-01-07 2026-01-10

SAAS-013: Email Module

Metadata

Campo Valor
Codigo SAAS-013
Modulo Email
Prioridad P1
Estado Completado
Fase 5 - Integraciones
Sprint Sprint 4
Fecha Implementacion 2026-01-07
Ultima Actualizacion 2026-01-10

Descripcion

Modulo de email con soporte multi-proveedor (SendGrid, AWS SES, SMTP) integrado con el sistema de notificaciones. Permite a los tenants enviar correos electronicos transaccionales, notificaciones y comunicaciones personalizadas utilizando templates y variables dinamicas.


Objetivos

  1. Proporcionar un sistema de envio de email robusto y multi-proveedor
  2. Permitir envio de emails simples (texto/HTML) y con templates
  3. Soportar attachments y campos CC/BCC
  4. Integrarse con el modulo de notificaciones existente
  5. Implementar fallback logging cuando no hay proveedor configurado
  6. Soportar bulk email con batches

Alcance

Incluido

  • Envio de emails simples (texto/HTML)
  • Templates con variables dinamicas
  • Soporte para attachments (base64)
  • Campos CC/BCC
  • Bulk email (batches de 10)
  • Fallback logging cuando no hay proveedor configurado
  • Integracion con sistema de notificaciones
  • Multi-proveedor: SendGrid, AWS SES, SMTP

Excluido

  • Email marketing masivo
  • Tracking de opens/clicks (futuro)
  • Templates almacenados en base de datos (futuro)
  • Queue de emails con BullMQ (futuro)
  • Rate limiting por tenant (futuro)

Proveedores Soportados

Proveedor Estado Notas
SendGrid Completado API v3
AWS SES Completado SES v2 (simplificado)
SMTP Parcial Requiere nodemailer

Arquitectura

apps/backend/src/modules/email/
├── email.module.ts          # Modulo global
├── index.ts
├── dto/
│   ├── send-email.dto.ts    # DTOs de envio
│   └── index.ts
├── services/
│   ├── email.service.ts     # Servicio principal
│   └── index.ts
└── templates/               # Templates (futuro)

Configuracion

Variables de Entorno

# Provider selection
EMAIL_PROVIDER=sendgrid          # sendgrid | ses | smtp

# Common settings
EMAIL_FROM=noreply@example.com
EMAIL_FROM_NAME=Template SaaS
EMAIL_REPLY_TO=support@example.com

# SendGrid
SENDGRID_API_KEY=SG.xxxxx

# AWS SES
AWS_SES_REGION=us-east-1
AWS_SES_ACCESS_KEY_ID=AKIAXXXXXXX
AWS_SES_SECRET_ACCESS_KEY=xxxxx

# SMTP (fallback)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=user
SMTP_PASSWORD=password
SMTP_SECURE=false

API del Servicio

sendEmail(dto: SendEmailDto): Promise

await emailService.sendEmail({
  to: { email: 'user@example.com', name: 'User Name' },
  subject: 'Welcome!',
  html: '<h1>Welcome</h1>',
  text: 'Welcome',
  cc: [{ email: 'copy@example.com' }],
  attachments: [{
    filename: 'doc.pdf',
    content: 'base64...',
    contentType: 'application/pdf'
  }]
});

sendTemplateEmail(dto: SendTemplateEmailDto): Promise

await emailService.sendTemplateEmail({
  to: { email: 'user@example.com' },
  templateKey: 'welcome',
  variables: {
    userName: 'John',
    appName: 'Template SaaS'
  }
});

Templates Incluidos

Key Descripcion
welcome Email de bienvenida
password_reset Reset de contrasena
invitation Invitacion a tenant
notification Notificacion generica

Estructura de Respuesta

interface EmailResult {
  success: boolean;
  messageId?: string;
  provider: 'sendgrid' | 'ses' | 'smtp';
  error?: string;
}

Integracion con Notificaciones

El modulo de email esta integrado con NotificationsService. Cuando se crea una notificacion con channel: 'email':

await notificationsService.create({
  userId: 'uuid',
  channel: 'email',
  email: 'user@example.com',     // Requerido para email
  userName: 'User Name',          // Opcional
  title: 'Subject',
  message: 'Body content',
  actionUrl: 'https://app.com/action'
}, tenantId);

Comportamiento sin Configuracion

Cuando no hay proveedor configurado:

  • Los emails se loguean en consola
  • EmailResult.success = true
  • EmailResult.messageId = 'mock-{timestamp}'

Entregables

  • EmailModule backend con servicio multi-proveedor
  • DTOs validados (send-email.dto.ts)
  • Integracion con NotificationsService
  • Soporte SendGrid API v3
  • Soporte AWS SES v2
  • Fallback logging para desarrollo

Criterios de Aceptacion

  • Envio de email simple (texto/HTML) funciona
  • Envio con template funciona
  • Attachments se envian correctamente
  • CC/BCC funcionan
  • Fallback logging funciona sin proveedor
  • Integracion con notificaciones funciona

Archivos Creados

Archivo Descripcion
modules/email/email.module.ts Modulo global
modules/email/services/email.service.ts Servicio multi-proveedor
modules/email/dto/send-email.dto.ts DTOs validados
config/env.config.ts Variables de email

Archivos Modificados

Archivo Cambio
app.module.ts Import EmailModule
notifications/services/notifications.service.ts Integracion EmailService
notifications/dto/create-notification.dto.ts Campos email, userName

Dependencias

Modulo Tipo Descripcion
SAAS-002 (Tenants) Requerido tenant_id en operaciones
SAAS-007 (Notifications) Requerido Canal de notificacion

Proximos Pasos

  1. Implementar SMTP con nodemailer
  2. AWS SES con SDK v3 (firma v4)
  3. Templates desde DB (notification_templates)
  4. Queue de emails con BullMQ
  5. Tracking de opens/clicks
  6. Rate limiting por tenant

Referencias


Ultima actualizacion: 2026-01-10 Version: 1.0.0 Autor: Claude Code (Reestructuracion Documental)