Skip to main content

Mail Service API

The Mail Service provides secure email sending capabilities across your organization’s applications. It supports configurable SMTP settings and various email templates for different use cases including authentication, password reset, account creation, user invitations, and security alerts.

Base URL

All endpoints are prefixed with /api/v1

Authentication

All endpoints require authentication via Bearer token with specific scopes:
Authorization: Bearer YOUR_TOKEN
Token Scopes:
  • SEND_MAIL - Required for sending emails
  • FETCH_CONFIG - Required for updating SMTP configuration

Architecture Overview

The Mail Service is built on a Node.js backend with MongoDB for data persistence. It uses a container-based dependency injection pattern with InversifyJS for better modularity. The service leverages configurable SMTP settings to send emails through various providers and integrates with:
  • Configuration Manager - Manages SMTP provider configurations
  • Authentication Service - Provides JWT token validation
  • MongoDB - Stores email metadata and tracking information

Key Features

  • Template-Based Emails - Pre-built templates for common use cases
  • SMTP Configuration - Flexible SMTP provider support
  • Email Tracking - Maintains records of sent emails
  • Authentication Integration - Secure token-based access
  • Attachment Support - File attachment capabilities
  • CC/BCC Support - Multiple recipient management

Supported Email Templates

The Mail Service includes built-in templates for:
  1. Login with OTP - One-time password authentication emails
  2. Reset Password - Password reset link emails
  3. Account Creation - Welcome emails for new users
  4. App User Invite - User invitation emails
  5. Suspicious Login Attempt - Security alert notifications

API Endpoints

Core email sending functionality with template support and SMTP configuration management.
Send an email using configured SMTP settings and specified template.
  • Request
  • Response
  • Error Responses
Endpoint: POST /api/v1/emails/sendEmailAuthentication: Requires scoped token with SEND_MAIL scopeRequest Body Parameters:
ParameterTypeRequiredDescription
emailTemplateTypestringYesType of email template (loginWithOTP, resetPassword, accountCreation, appuserInvite, suspiciousLoginAttempt)
sendEmailTostring[]YesArray of recipient email addresses
subjectstringYesEmail subject line
templateDataobjectYesData to populate the email template
sendCcTostring[]NoArray of CC recipient email addresses
attachmentsobject[]NoArray of email attachments
fromEmailDomainstringNoOverride sender email domain
productNamestringNoProduct name for branding
isAutoEmailbooleanNoFlag indicating automated email
Email Template Types:
  • loginWithOTP - One-time password authentication
  • resetPassword - Password reset emails
  • accountCreation - New account welcome emails
  • appuserInvite - User invitation emails
  • suspiciousLoginAttempt - Security alert emails
Template Data Structure: The templateData object should contain template-specific variables. Common fields include:
  • userName - Recipient’s name
  • companyName - Organization name
  • otp - One-time password (for OTP emails)
  • resetLink - Password reset URL (for reset emails)
  • inviteLink - Invitation URL (for invite emails)
{
  "emailTemplateType": "loginWithOTP",
  "sendEmailTo": ["user@example.com"],
  "subject": "Your Login OTP",
  "templateData": {
    "userName": "John Doe",
    "companyName": "Example Corp",
    "otp": "123456"
  },
  "sendCcTo": ["admin@example.com"],
  "attachments": [
    {
      "filename": "document.pdf",
      "content": "base64-encoded-content",
      "contentType": "application/pdf"
    }
  ]
}
Update the SMTP configuration for the mail service.
  • Request
  • Response
  • Error Responses
Endpoint: POST /api/v1/updateSmtpConfigAuthentication: Requires scoped token with FETCH_CONFIG scopeRequest Body Parameters: No request body required. The configuration is loaded from the Configuration Manager service.SMTP Configuration Schema: The SMTP configuration includes:
  • host - SMTP server hostname
  • port - SMTP server port (default: 587)
  • username - SMTP authentication username (optional)
  • password - SMTP authentication password (optional)
  • fromEmail - Default sender email address

Middleware and Validation

The Mail Service implements several middleware layers for security and validation:

SMTP Configuration Checker

Validates that SMTP configuration is properly set before allowing email operations:
  • Checks for required SMTP settings (host, port, fromEmail)
  • Ensures configuration completeness
  • Prevents email sending without proper setup

JWT Token Validation

Validates Bearer tokens for authentication:
  • Verifies token signature and validity
  • Extracts user information from token payload
  • Ensures proper authorization for operations

Container-Based Architecture

Uses InversifyJS dependency injection for:
  • Service lifecycle management
  • Configuration updates without service restart
  • Modular component organization

Email Template System

The service uses Handlebars templating engine with:

Template Structure

  • Layouts - Main email structure templates
  • Partials - Reusable template components (header, footer, head)
  • Helpers - Custom Handlebars helpers for conditional rendering

Template Features

  • Responsive email design
  • Consistent styling across templates
  • Dynamic content population
  • Conditional content rendering
  • Task table support for structured data

Styling System

Automated styling injection includes:
  • Container and table styling
  • Mobile-responsive design
  • Button and form styling
  • Consistent color scheme and typography

Schema Definitions

  • Mail Info Schema
  • Mail Body Schema
  • SMTP Config Schema
  • Email Template Types
  • Mail Config Schema
interface MailInfo extends Document {
  orgId: Types.ObjectId;
  subject: string;
  from: string;
  to: string[]; // Array of recipient email addresses
  cc?: string[]; // Array of CC recipient email addresses
  emailTemplateType: string; // Template type used
  createdAt?: Date;
  updatedAt?: Date;
}

Error Handling

All endpoints return structured error responses:
{
  "error": {
    "message": "Error description",
    "code": "ERROR_CODE",
    "details": "Additional error information"
  }
}
Common Error Scenarios:
  • SMTP Not Configured - Service requires SMTP configuration before sending emails
  • Invalid Template - Unknown email template type specified
  • Authentication Failed - Invalid or missing JWT token
  • Email Send Failure - SMTP server errors or network issues
  • Invalid Recipients - Malformed email addresses
  • Missing Required Fields - Required parameters not provided

Email Delivery Process

  1. Configuration Validation
    • Verify SMTP configuration exists
    • Validate authentication credentials
    • Check required fields
  2. Template Processing
    • Select appropriate email template
    • Populate template with provided data
    • Apply styling and formatting
    • Handle conditional content
  3. Email Composition
    • Set sender and recipient information
    • Attach files if provided
    • Configure email headers
    • Apply SMTP settings
  4. Delivery and Tracking
    • Send email via configured SMTP provider
    • Record email metadata in database
    • Return delivery confirmation
    • Handle delivery errors gracefully

Security Considerations

  • Token-Based Authentication - All endpoints require valid JWT tokens with appropriate scopes
  • SMTP Credential Protection - Passwords are not returned in API responses
  • Input Validation - Email addresses and template data are validated
  • Error Handling - Sensitive information is not exposed in error messages
  • Container Security - Dependency injection prevents unauthorized access to services

Important Notes

  1. SMTP Configuration Required - Email sending requires proper SMTP configuration
  2. Template Data Validation - Template data must match expected template variables
  3. Email Tracking - All sent emails are automatically logged in MongoDB
  4. Attachment Support - Files can be attached using base64 encoding
  5. Responsive Templates - Email templates are mobile-responsive by default
  6. Error Recovery - Service handles SMTP failures gracefully without crashing
  7. Configuration Updates - SMTP settings can be updated without service restart
  8. Token Scopes - Different operations require different token scopes for security
I