Skip to main content

Email Service Module

The Email Service module is a comprehensive email communication system for the Comdeall platform that manages all email operations including transactional emails, template-based messaging, multi-provider failover support, and background job processing. It integrates with multiple email providers (Brevo, Resend, Mailjet) to ensure reliable email delivery with automatic failover capabilities and sophisticated retry mechanisms for user registration, OTP verification, wallet operations, and support communications.

Table of Contents

  1. Module Structure
  2. Email Endpoints
  3. Core Features
  4. Email Providers
  5. Template Management
  6. Background Processing
  7. Integration Points
  8. Technical Implementation
  9. Security Considerations
  10. Error Handling
  11. Conclusion

Module Structure

The Email Service module follows a provider-based architecture with automatic failover capabilities:

@Module({
controllers: [EmailController],
providers: [
EmailService,
BrevoProvider,
ResendProvider,
MailjetProvider,
{
provide: 'EmailProvider',
useFactory: (brevo: BrevoProvider, resend: ResendProvider, mailjet: MailjetProvider) => {
return new FailoverProvider([brevo, resend, mailjet]);
},
inject: [BrevoProvider, ResendProvider, MailjetProvider],
},
],
exports: [EmailService],
})
export class EmailModule {}

Core Components:

  1. Controller Layer (email.controller.ts): Handles admin email sending endpoints with template selection and validation

  2. Service Layer (email.service.ts): Implements template routing, email composition, and provider coordination

  3. Provider Layer (providers/): Multiple email service providers with automatic failover orchestration

  4. Queue Service (email-queue.service.ts): Background job processing for asynchronous email delivery

  5. Database Layer: Integrates with user management and notification systems for email validation and delivery tracking

Email Endpoints

EndpointMethodDescriptionAuth Type
/communication/send-emailPOSTSend templated email (Admin only)JWT (Admin)

Core Features

Multi-Provider Email Delivery

The email system implements automatic failover across multiple providers to ensure high deliverability rates and system reliability.

Provider Hierarchy:

  • Primary Provider: Brevo (Sendinblue) for high deliverability and transactional email specialization
  • Secondary Provider: Resend for developer-friendly API and modern email infrastructure
  • Tertiary Provider: Mailjet for enterprise features and additional redundancy

Failover Logic: The system attempts providers sequentially until successful delivery, with comprehensive error logging and automatic fallback to the next available provider.

Template-Based Email System

The module implements a comprehensive template system with pre-built email templates for all user communication scenarios:

Template Categories:

  • Authentication: Registration confirmations, OTP verification emails
  • Financial: Wallet withdrawal requests and failure notifications
  • Support: Ticket resolutions and note addition notifications
  • System: Dead letter queue alerts for development team

Template Features:

  • Dynamic content substitution with user-specific variables
  • Responsive HTML design with plain-text fallback versions
  • Consistent Comdeall branding and styling across all communications
  • Multi-language support preparation for future internationalization

Background Job Processing

Email delivery is handled asynchronously through a robust queue system to prevent blocking user operations:

Queue Management:

  • Bull queue integration for reliable job processing and retry mechanisms
  • Exponential backoff for failed email attempts with configurable retry limits
  • Dead letter queue monitoring for permanently failed jobs with developer alerts
  • Job prioritization based on email type and urgency

Performance Benefits:

  • Non-blocking email operations that don't impact user experience
  • Batch processing capabilities for bulk email campaigns
  • Resource optimization through connection pooling and rate limiting
  • Scalable architecture supporting high-volume email processing

Email Providers

Brevo Provider (Primary)

Brevo serves as the primary email provider with specialized transactional email capabilities:

Configuration Requirements:

// Environment variables
BREVO_API_KEY=your_brevo_api_key
SENDER_EMAIL=noreply@comdeall.com
SENDER_NAME=Com DEALL Team

Key Features:

  • High deliverability rates with dedicated IP options
  • Advanced analytics and delivery tracking
  • GDPR compliance and data protection features
  • Specialized transactional email optimization

Failover Provider Architecture

The FailoverProvider orchestrates multiple email providers with intelligent routing:

Failover Strategy:

// Sequential provider attempt with error handling
for (const provider of this.providers) {
try {
const response = await provider.sendEmail(data);
return response; // Success - return immediately
} catch (error) {
// Log error and continue to next provider
}
}

Error Handling:

  • Provider-specific error categorization and logging
  • Network timeout handling with configurable retry intervals
  • Rate limiting detection with automatic provider switching
  • Comprehensive monitoring and alerting for provider health

Template Management

Email Template Structure

Each email template includes comprehensive formatting and content management:

Template Components:

  • Subject Line: Descriptive and branded subject lines with emoji support
  • Text Version: Plain-text content for accessibility and spam filter compatibility
  • HTML Version: Responsive design with mobile optimization and rich formatting
  • Variable Substitution: Dynamic content injection with type-safe parameter validation

Template Types and Usage

Registration Email

  • Purpose: Welcome new users after successful registration
  • Variables: User name for personalization
  • Content: Onboarding instructions and application access information

OTP Verification Email

  • Purpose: Deliver one-time passwords for email verification
  • Variables: OTP code with security formatting
  • Security Features: Time limit warnings and security best practices

Wallet Operation Emails

  • Purpose: Transaction confirmations and failure notifications
  • Variables: Transaction amounts and status information
  • Compliance: Financial communication standards and audit trails

Support Communication Emails

  • Purpose: Ticket resolutions and support note notifications
  • Variables: Ticket details and note content
  • Integration: Support workflow automation and status tracking

Dead Letter Queue Alerts

  • Purpose: System alerts for failed background jobs
  • Recipients: Development team for system monitoring
  • Content: Detailed error information and debugging data

Background Processing

Email Queue Architecture

The background processing system handles all email operations asynchronously:

Job Types:

  • IRegistrationEmailJob: New user welcome emails
  • IOtpEmailJob: OTP verification email delivery
  • IWithdrawWalletRequestEmailJob: Wallet withdrawal confirmations
  • IWithdrawWalletRequestFailureEmailJob: Withdrawal failure notifications
  • ISupportTicketResolvedEmailJob: Support ticket resolution emails
  • INoteAddedEmailJob: Support note addition notifications
  • IDeadLetterQueueEmailJob: System alert emails for failed jobs

Queue Processing Flow

Email Processing Workflow:

  1. Job Creation: Background services queue email jobs with appropriate priority and data
  2. Template Resolution: EmailQueueService maps job data to corresponding email templates
  3. Content Generation: Dynamic content injection and template compilation
  4. Provider Selection: FailoverProvider handles delivery with automatic fallback
  5. Retry Logic: Failed jobs retry with exponential backoff and maximum attempt limits
  6. Dead Letter Queue: Permanently failed jobs trigger developer alerts and manual intervention

Integration Points

User Management Integration

The email service integrates seamlessly with user management workflows:

User Lifecycle Events:

  • Registration confirmations sent automatically upon user creation
  • OTP delivery integrated with authentication verification flows
  • Profile update notifications for important account changes
  • Account status change communications for administrative actions

Support System Integration

Email automation supports the customer support workflow:

Support Integration Features:

  • Automatic ticket resolution notifications to users
  • Support note addition emails for transparency
  • Escalation notifications for high-priority issues
  • Satisfaction survey delivery post-resolution

Financial System Integration

Wallet and payment operations trigger automated email communications:

Financial Email Automation:

  • Withdrawal request confirmations with transaction details
  • Failure notifications with clear next steps and support information
  • Transaction completion confirmations for audit trails
  • Payment reminder systems for subscription management

Notification System Coordination

Email delivery coordinates with push notification systems:

Multi-Channel Communication:

  • Synchronized messaging across email and push notifications
  • Preference management for communication channel selection
  • Fallback email delivery when push notifications fail
  • Unified notification history and delivery tracking

Technical Implementation

Provider Interface Design

All email providers implement a common interface for seamless integration:

interface EmailProvider {
sendEmail(data: SendEmailDataDto): Promise<SendEmailResponse>;
}

Implementation Benefits:

  • Consistent API across all provider implementations
  • Easy addition of new email providers without code changes
  • Standardized error handling and response formatting
  • Simplified testing and mocking for development

Template System Architecture

The template system uses a factory pattern for dynamic template generation:

Template Factory Features:

  • Type-safe template parameter validation
  • Consistent styling and branding across all templates
  • Dynamic content injection with XSS protection
  • Template versioning for A/B testing and improvements

Database Integration

Email operations integrate with database triggers and functions:

Database Email Validation:

  • Email format validation using regex patterns in database triggers
  • Performance-optimized email lookup indexes
  • User email change tracking for security monitoring
  • Email delivery status tracking for analytics and compliance

Security Considerations

Email Content Security

All email content undergoes security validation and sanitization:

Security Measures:

  • XSS prevention in dynamic content injection
  • Template injection protection through parameter validation
  • Secure handling of sensitive information in email content
  • Spam filter optimization to ensure delivery success

Provider Security Management

Email provider credentials and API keys are managed securely:

Credential Management:

  • Environment variable storage for API keys and secrets
  • Rotation policies for provider authentication credentials
  • Audit logging for all provider authentication attempts
  • Secure connection requirements for all provider communications

Email Delivery Security

The system implements security measures for reliable and secure email delivery:

Delivery Security Features:

  • SPF, DKIM, and DMARC configuration for domain authentication
  • Bounce and complaint handling to maintain sender reputation
  • Rate limiting to prevent abuse and maintain provider relationships
  • Recipient validation to prevent invalid email address processing

Error Handling

The module implements comprehensive error handling with specific categorization:

Error Categories:

  • Provider Errors: API failures, rate limiting, authentication issues
  • Template Errors: Invalid parameters, missing variables, formatting issues
  • Delivery Errors: Bounce handling, spam filter rejections, recipient issues
  • System Errors: Queue failures, database connectivity, configuration problems

Error Response Management: All errors include appropriate logging levels, structured error codes for debugging, and automated alerting for critical failures requiring immediate attention.

Conclusion

The Email Service module provides a robust, scalable, and reliable email communication system for the Comdeall platform. Key strengths include:

Multi-Provider Reliability:

  • Automatic failover ensures high delivery rates and system availability
  • Provider diversity reduces single points of failure and service dependencies
  • Intelligent routing optimizes delivery success rates and performance

Template-Based Communication:

  • Consistent branding and messaging across all user communications
  • Dynamic content injection with security validation and type safety
  • Responsive design ensuring optimal display across all email clients

Background Processing:

  • Asynchronous email operations prevent blocking user interactions
  • Robust retry mechanisms with exponential backoff ensure delivery success
  • Dead letter queue monitoring provides visibility into system health

Integration Benefits:

  • Seamless coordination with user management, support, and financial systems
  • Multi-channel communication coordination with push notification systems
  • Comprehensive audit logging for compliance and analytics requirements

The module's architecture supports the diverse communication needs of the child development platform, ensuring reliable delivery of critical information to parents, therapists, and administrators while maintaining high security standards and optimal performance.