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

289 lines
6.3 KiB
Markdown

---
id: "SAAS-013"
title: "Email Module"
type: "Module"
status: "Published"
priority: "P1"
module: "email"
version: "1.0.0"
created_date: "2026-01-07"
updated_date: "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
```env
# 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<EmailResult>
```typescript
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<EmailResult>
```typescript
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
```typescript
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'`:
```typescript
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
- [x] EmailModule backend con servicio multi-proveedor
- [x] DTOs validados (send-email.dto.ts)
- [x] Integracion con NotificationsService
- [x] Soporte SendGrid API v3
- [x] Soporte AWS SES v2
- [x] Fallback logging para desarrollo
---
## Criterios de Aceptacion
- [x] Envio de email simple (texto/HTML) funciona
- [x] Envio con template funciona
- [x] Attachments se envian correctamente
- [x] CC/BCC funcionan
- [x] Fallback logging funciona sin proveedor
- [x] 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
- [INT-003-email](../02-integraciones/INT-003-email.md)
- [SAAS-007-notifications](./SAAS-007-notifications.md)
- [SendGrid API v3](https://docs.sendgrid.com/api-reference)
- [AWS SES v2 API](https://docs.aws.amazon.com/ses/latest/APIReference-V2/)
- [Nodemailer](https://nodemailer.com/)
---
**Ultima actualizacion:** 2026-01-10
**Version:** 1.0.0
**Autor:** Claude Code (Reestructuracion Documental)