> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pipeshub.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Mail service

# 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:

```http theme={null}
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

<AccordionGroup>
  <Accordion title="Email Operations">
    Core email sending functionality with template support and SMTP configuration management.

    <AccordionGroup>
      <Accordion title="POST /emails/sendEmail - Send Email">
        Send an email using configured SMTP settings and specified template.

        <Tabs>
          <Tab title="Request">
            **Endpoint:** `POST /api/v1/emails/sendEmail`

            **Authentication:** Requires scoped token with `SEND_MAIL` scope

            **Request Body Parameters:**

            | Parameter         | Type      | Required | Description                                                                                                  |
            | ----------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------ |
            | emailTemplateType | string    | Yes      | Type of email template (loginWithOTP, resetPassword, accountCreation, appuserInvite, suspiciousLoginAttempt) |
            | sendEmailTo       | string\[] | Yes      | Array of recipient email addresses                                                                           |
            | subject           | string    | Yes      | Email subject line                                                                                           |
            | templateData      | object    | Yes      | Data to populate the email template                                                                          |
            | sendCcTo          | string\[] | No       | Array of CC recipient email addresses                                                                        |
            | attachments       | object\[] | No       | Array of email attachments                                                                                   |
            | fromEmailDomain   | string    | No       | Override sender email domain                                                                                 |
            | productName       | string    | No       | Product name for branding                                                                                    |
            | isAutoEmail       | boolean   | No       | Flag 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)

            ```json theme={null}
            {
              "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"
                }
              ]
            }
            ```
          </Tab>

          <Tab title="Response">
            **Status:** `200 OK`

            ```json theme={null}
            {
              "data": {
                "status": true,
                "data": "Email sent"
              }
            }
            ```

            **Email Record Creation:**
            Upon successful email sending, a record is automatically created in MongoDB with the following information:

            * Subject and sender details
            * Recipient and CC lists
            * Email template type used
            * Timestamp information
          </Tab>

          <Tab title="Error Responses">
            **Status:** `404 Not Found`

            ```json theme={null}
            {
              "error": {
                "message": "Smtp Configuration not set"
              }
            }
            ```

            **Status:** `500 Internal Server Error`

            ```json theme={null}
            {
              "error": {
                "message": "Error sending mail"
              }
            }
            ```

            **Status:** `400 Bad Request`

            ```json theme={null}
            {
              "error": {
                "message": "Unknown Template"
              }
            }
            ```

            **Status:** `400 Bad Request`

            ```json theme={null}
            {
              "error": {
                "message": "Smtp not configured properly"
              }
            }
            ```

            **Status:** `401 Unauthorized`

            ```json theme={null}
            {
              "error": {
                "message": "Authorization header not found"
              }
            }
            ```

            **Status:** \`403 Forbidden\*\*

            ```json theme={null}
            {
              "error": {
                "message": "Invalid token scope"
              }
            }
            ```
          </Tab>
        </Tabs>
      </Accordion>

      <Accordion title="POST /updateSmtpConfig - Update SMTP Configuration">
        Update the SMTP configuration for the mail service.

        <Tabs>
          <Tab title="Request">
            **Endpoint:** `POST /api/v1/updateSmtpConfig`

            **Authentication:** Requires scoped token with `FETCH_CONFIG` scope

            **Request 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
          </Tab>

          <Tab title="Response">
            **Status:** `200 OK`

            ```json theme={null}
            {
              "message": "SMTP configuration updated successfully",
              "smtp": {
                "host": "smtp.example.com",
                "port": 587,
                "fromEmail": "no-reply@example.com",
                "username": "smtp-user"
              }
            }
            ```

            **Note:** Password is not returned in the response for security reasons.
          </Tab>

          <Tab title="Error Responses">
            **Status:** `401 Unauthorized`

            ```json theme={null}
            {
              "error": {
                "message": "Authorization header not found"
              }
            }
            ```

            **Status:** `403 Forbidden`

            ```json theme={null}
            {
              "error": {
                "message": "Invalid token scope"
              }
            }
            ```

            **Status:** `404 Not Found`

            ```json theme={null}
            {
              "error": {
                "message": "Mail container not found"
              }
            }
            ```
          </Tab>
        </Tabs>
      </Accordion>
    </AccordionGroup>
  </Accordion>
</AccordionGroup>

## 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

<Tabs>
  <Tab title="Mail Info Schema">
    ```typescript theme={null}
    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;
    }
    ```
  </Tab>

  <Tab title="Mail Body Schema">
    ```typescript theme={null}
    interface MailBody {
      productName?: string; // Product name for branding
      emailTemplateType: string; // Required template type
      isAutoEmail?: boolean; // Flag for automated emails
      fromEmailDomain?: string; // Override sender domain
      sendEmailTo?: string[]; // Recipient email addresses
      subject?: string; // Email subject line
      templateData?: Record<string, any>; // Template variables
      sendCcTo?: string[]; // CC recipient email addresses
      attachments?: any[]; // Email attachments
    }
    ```
  </Tab>

  <Tab title="SMTP Config Schema">
    ```typescript theme={null}
    interface SmtpConfig {
      username?: string; // SMTP authentication username
      password?: string; // SMTP authentication password
      host: string; // SMTP server hostname (required)
      fromEmail: string; // Default sender email (required)
      port: number; // SMTP server port (required)
    }
    ```
  </Tab>

  <Tab title="Email Template Types">
    ```typescript theme={null}
    enum EmailTemplateType {
      LoginWithOtp = 'loginWithOTP',
      ResetPassword = 'resetPassword',
      AccountCreation = 'accountCreation',
      AppuserInvite = 'appuserInvite',
      SuspiciousLoginAttempt = 'suspiciousLoginAttempt'
    }
    ```
  </Tab>

  <Tab title="Mail Config Schema">
    ```typescript theme={null}
    interface MailConfig {
      jwtSecret: string; // JWT signing secret
      scopedJwtSecret: string; // Scoped token signing secret
      database: {
        url: string; // MongoDB connection URL
        dbName: string; // Database name
      };
      smtp: {
        username: string; // SMTP username
        password: string; // SMTP password
        host: string; // SMTP host
        port: number; // SMTP port
        fromEmail: string; // Default sender email
      };
    }
    ```
  </Tab>
</Tabs>

## Error Handling

All endpoints return structured error responses:

```json theme={null}
{
  "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
