UNPKG

backend-mcp

Version:

Generador automático de backends con Node.js, Express, Prisma y módulos configurables. Servidor MCP compatible con npx para agentes IA. Soporta PostgreSQL, MySQL, MongoDB y SQLite.

526 lines (425 loc) 10.9 kB
# 📦 Módulo email **Versión:** 1.0.0 **Categoría:** communication **Descripción:** Sistema completo de emails con templates, colas y múltiples proveedores ## 📊 Estado del Módulo | Componente | Estado | |------------|--------| | Script de inicialización | ✅ Disponible | | Templates | ✅ Disponible | | Ejemplos | ❌ Faltante | ## 🔗 Dependencias ### Requeridas - `database` ### Opcionales - `logging` - `auth` ## 🤖 Triggers para IA Este módulo se activa automáticamente cuando se detectan las siguientes palabras clave: - **user_wants_email**: true - **needs_notifications**: true - **requires_email_verification**: true - **has_password_reset**: true - **undefined**: undefined ## ✨ Características - multiple-providers - html-templates - email-queue - template-variables - attachment-support - email-tracking - retry-mechanism - bulk-emails - email-validation - unsubscribe-handling ## 📖 Documentación Completa # Módulo Email Módulo para gestión y envío de emails en aplicaciones backend con soporte para múltiples proveedores y plantillas. ## Características - ✅ Soporte para múltiples proveedores (SendGrid, Mailgun, AWS SES, SMTP) - ✅ Sistema de plantillas con Handlebars - ✅ Cola de emails para envío asíncrono - ✅ Validación de emails - ✅ Tracking de emails (abiertos, clicks) - ✅ Manejo de rebotes y quejas - ✅ Soporte para adjuntos - ✅ Emails transaccionales y marketing - ✅ Rate limiting y throttling - ✅ Logs y métricas de envío ## Configuración ### Requisitos - Node.js 16+ - Cuenta en proveedor de email (SendGrid, Mailgun, etc.) - Base de datos para cola de emails (opcional) ### Variables de Entorno ```bash # Configuración del proveedor de email EMAIL_PROVIDER=sendgrid # sendgrid, mailgun, ses, smtp EMAIL_API_KEY=your_api_key_here EMAIL_FROM_ADDRESS=noreply@example.com EMAIL_FROM_NAME="Mi Aplicación" # Configuración SMTP (si usas SMTP) SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your_email@gmail.com SMTP_PASS=your_password SMTP_SECURE=false # Configuración de cola EMAIL_QUEUE_ENABLED=true EMAIL_QUEUE_REDIS_URL=redis://localhost:6379 # Configuración de tracking EMAIL_TRACKING_ENABLED=true EMAIL_TRACKING_DOMAIN=track.example.com ``` ## Uso ### Configuración Básica ```javascript const { initEmail } = require('./modules/email'); // Configurar servicio de email const emailService = await initEmail({ provider: 'sendgrid', apiKey: process.env.EMAIL_API_KEY, from: { email: process.env.EMAIL_FROM_ADDRESS, name: process.env.EMAIL_FROM_NAME } }); ``` ### Envío de Email Simple ```javascript // Enviar email simple await emailService.send({ to: 'usuario@example.com', subject: 'Bienvenido a nuestra aplicación', text: 'Gracias por registrarte en nuestra aplicación.', html: '<h1>Bienvenido</h1><p>Gracias por registrarte.</p>' }); ``` ### Uso de Plantillas ```javascript // Enviar email con plantilla await emailService.sendTemplate({ to: 'usuario@example.com', template: 'welcome', data: { userName: 'Juan Pérez', activationLink: 'https://example.com/activate/123' } }); ``` ### Email con Adjuntos ```javascript // Enviar email con adjuntos await emailService.send({ to: 'usuario@example.com', subject: 'Factura adjunta', text: 'Adjunto encontrarás tu factura.', attachments: [ { filename: 'factura.pdf', path: './files/factura.pdf' }, { filename: 'logo.png', content: Buffer.from('...'), contentType: 'image/png' } ] }); ``` ## Plantillas ### Crear Plantilla ```handlebars <!-- templates/welcome.hbs --> <!DOCTYPE html> <html> <head> <title>Bienvenido {{userName}}</title> </head> <body> <h1>¡Hola {{userName}}!</h1> <p>Gracias por registrarte en nuestra aplicación.</p> <p> <a href="{{activationLink}}" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;"> Activar Cuenta </a> </p> <p>Si tienes alguna pregunta, no dudes en contactarnos.</p> <p>Saludos,<br>El equipo de {{appName}}</p> </body> </html> ``` ### Registrar Plantilla ```javascript // Registrar plantilla personalizada await emailService.registerTemplate('welcome', { subject: 'Bienvenido a {{appName}}', html: fs.readFileSync('./templates/welcome.hbs', 'utf8'), text: 'Hola {{userName}}, bienvenido a {{appName}}. Activa tu cuenta en: {{activationLink}}' }); ``` ## Cola de Emails ### Configurar Cola ```javascript // Configurar cola con Redis const emailService = await initEmail({ provider: 'sendgrid', apiKey: process.env.EMAIL_API_KEY, queue: { enabled: true, redis: { host: 'localhost', port: 6379 }, concurrency: 5, attempts: 3, backoff: { type: 'exponential', delay: 2000 } } }); ``` ### Envío Programado ```javascript // Programar email para envío posterior await emailService.schedule({ to: 'usuario@example.com', subject: 'Recordatorio', template: 'reminder', data: { userName: 'Juan' }, sendAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // En 24 horas }); ``` ## Tracking y Analytics ### Habilitar Tracking ```javascript // Configurar tracking const emailService = await initEmail({ provider: 'sendgrid', tracking: { enabled: true, domain: 'track.example.com', opens: true, clicks: true, unsubscribe: true } }); ``` ### Obtener Métricas ```javascript // Obtener estadísticas de envío const stats = await emailService.getStats({ from: '2024-01-01', to: '2024-01-31' }); console.log(stats); // { // sent: 1250, // delivered: 1200, // opens: 800, // clicks: 150, // bounces: 25, // complaints: 5 // } ``` ## Validación de Emails ### Validar Email ```javascript // Validar dirección de email const isValid = await emailService.validateEmail('usuario@example.com'); // Validación avanzada const validation = await emailService.validateEmailAdvanced('usuario@example.com'); console.log(validation); // { // valid: true, // reason: 'valid', // risk: 'low', // disposable: false, // role: false // } ``` ## Manejo de Webhooks ### Configurar Webhooks ```javascript // Configurar manejo de webhooks await emailService.setupWebhooks({ endpoint: '/webhooks/email', events: ['delivered', 'opened', 'clicked', 'bounced', 'complained'] }); // Manejar eventos de webhook emailService.on('email.delivered', (event) => { console.log(`Email entregado: ${event.email}`); }); emailService.on('email.bounced', (event) => { console.log(`Email rebotó: ${event.email}, razón: ${event.reason}`); }); ``` ## Configuración Avanzada ### Múltiples Proveedores ```javascript // Configurar failover entre proveedores const emailService = await initEmail({ providers: [ { name: 'primary', type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY, priority: 1 }, { name: 'backup', type: 'mailgun', apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN, priority: 2 } ], failover: { enabled: true, retryDelay: 5000 } }); ``` ### Rate Limiting ```javascript // Configurar límites de envío const emailService = await initEmail({ provider: 'sendgrid', rateLimit: { max: 100, // 100 emails por ventana window: 60000, // 1 minuto skipSuccessfulRequests: false } }); ``` ### Segmentación ```javascript // Envío masivo con segmentación await emailService.sendBulk({ template: 'newsletter', segments: [ { name: 'premium_users', recipients: ['user1@example.com', 'user2@example.com'], data: { tier: 'premium' } }, { name: 'free_users', recipients: ['user3@example.com', 'user4@example.com'], data: { tier: 'free' } } ] }); ``` ## Testing ### Modo de Prueba ```javascript // Configurar modo de prueba const emailService = await initEmail({ provider: 'sendgrid', testMode: true, // No envía emails reales testEmail: 'test@example.com' // Redirige todos los emails aquí }); ``` ### Tests Unitarios ```javascript // Ejemplo de test const { EmailService } = require('./modules/email'); describe('EmailService', () => { let emailService; beforeEach(async () => { emailService = new EmailService({ provider: 'mock', testMode: true }); }); test('should send email successfully', async () => { const result = await emailService.send({ to: 'test@example.com', subject: 'Test', text: 'Test message' }); expect(result.success).toBe(true); expect(result.messageId).toBeDefined(); }); }); ``` ## Troubleshooting ### Errores Comunes 1. **Email no se envía** - Verificar API key del proveedor - Comprobar límites de envío - Revisar configuración de DNS 2. **Emails van a spam** - Configurar SPF, DKIM y DMARC - Usar dominio verificado - Evitar contenido spam 3. **Alta tasa de rebotes** - Validar emails antes de enviar - Limpiar lista de contactos - Monitorear reputación del dominio ### Logs y Debugging ```javascript // Habilitar logs detallados const emailService = await initEmail({ provider: 'sendgrid', debug: true, logger: { level: 'debug', format: 'json' } }); // Ver logs de envío emailService.on('email.sent', (event) => { console.log('Email enviado:', event); }); emailService.on('email.failed', (event) => { console.error('Error enviando email:', event.error); }); ``` ### Monitoreo ```javascript // Métricas de rendimiento const metrics = await emailService.getMetrics(); console.log({ queueSize: metrics.queue.size, processing: metrics.queue.processing, failed: metrics.queue.failed, rateLimit: metrics.rateLimit.remaining }); ``` ## API Reference ### EmailService #### `send(options)` Envía un email individual. **Parámetros:** - `to` (string|array): Destinatario(s) - `subject` (string): Asunto del email - `text` (string): Contenido en texto plano - `html` (string): Contenido en HTML - `attachments` (array): Archivos adjuntos #### `sendTemplate(options)` Envía un email usando una plantilla. **Parámetros:** - `to` (string|array): Destinatario(s) - `template` (string): Nombre de la plantilla - `data` (object): Datos para la plantilla #### `schedule(options)` Programa un email para envío posterior. **Parámetros:** - `sendAt` (Date): Fecha y hora de envío - Resto de parámetros como `send()` ## Contribuir Para contribuir a este módulo: 1. Fork el repositorio 2. Crea una rama para tu feature 3. Añade tests para nuevas funcionalidades 4. Ejecuta `npm test` para verificar 5. Crea un Pull Request ## Licencia MIT License - ver archivo LICENSE para más detalles. ## 🔗 Enlaces - [Volver al índice de módulos](./README.md) - [Documentación principal](../README.md) - [Código fuente](../../modules/email/)