Sign inSign up

kunalghoshone/imap-smtp

By kunalghoshone

โ€ขUpdated about 1 year ago

Go to this https://github.com/kunalGhoshOne/imap-smtp/tree/master

Image
Networking
Integration & delivery
API management
0

330

kunalghoshone/imap-smtp repository overview

https://github.com/kunalGhoshOne/imap-smtp/tree/masterโ 

โ Modular SMTP/IMAP/LMTP Server

A comprehensive Node.js email server that supports SMTP (sending), IMAP (retrieval), and LMTP (local transfer) protocols with modular architecture, mailbox management, and Docker deployment.

โ ๐Ÿ—๏ธ Architecture

The application is organized into modular components with clear separation of concerns:

smtp-nodejs/
โ”œโ”€โ”€ config/           # Configuration management
โ”‚   โ”œโ”€โ”€ config.js     # Centralized configuration
โ”‚   โ””โ”€โ”€ database.js   # Database connection management
โ”œโ”€โ”€ models/           # Database models
โ”‚   โ”œโ”€โ”€ Email.js      # Email schema and model
โ”‚   โ””โ”€โ”€ Mailbox.js    # Mailbox schema and model
โ”œโ”€โ”€ services/         # Business logic services
โ”‚   โ”œโ”€โ”€ MultiPortSMTPServer.js # Multi-port SMTP server
โ”‚   โ”œโ”€โ”€ IMAPServer.js # IMAP server with modular commands
โ”‚   โ”œโ”€โ”€ LMTPServer.js # LMTP server
โ”‚   โ”œโ”€โ”€ EmailProcessor.js # Email processing logic
โ”‚   โ”œโ”€โ”€ MailSender.js # External email delivery
โ”‚   โ”œโ”€โ”€ EmailQueue.js # Queue management
โ”‚   โ”œโ”€โ”€ QueueAPI.js   # Web dashboard and API
โ”‚   โ”œโ”€โ”€ MailboxAPI.js # Mailbox management API
โ”‚   โ””โ”€โ”€ IPSelectionService.js # Dynamic IP selection
โ”œโ”€โ”€ services/imap/commands/ # Modular IMAP command handlers
โ”‚   โ”œโ”€โ”€ CapabilityCommand.js
โ”‚   โ”œโ”€โ”€ LoginCommand.js
โ”‚   โ”œโ”€โ”€ SelectCommand.js
โ”‚   โ”œโ”€โ”€ FetchCommand.js
โ”‚   โ”œโ”€โ”€ SearchCommand.js
โ”‚   โ”œโ”€โ”€ SortCommand.js
โ”‚   โ””โ”€โ”€ UIDCommand.js
โ”œโ”€โ”€ utils/            # Utility modules
โ”‚   โ””โ”€โ”€ logger.js     # Centralized logging
โ”œโ”€โ”€ server.js         # Main application entry point
โ”œโ”€โ”€ Dockerfile        # Docker container definition
โ”œโ”€โ”€ docker-compose.yml # Multi-service deployment
โ””โ”€โ”€ package.json      # Dependencies and scripts

โ ๐Ÿš€ Features

  • Modular Architecture: Clean separation of concerns with dedicated modules
  • Multi-Protocol Support: SMTP, IMAP, and LMTP servers
  • SMTP Protocol Support: Full SMTP command handling (HELO, MAIL FROM, RCPT TO, DATA, QUIT, RSET)
  • IMAP Protocol Support: Complete IMAP implementation with modular command handlers
  • LMTP Protocol Support: Local mail transfer protocol implementation
  • Email Processing: MIME parsing with attachment support
  • Multi-Port SMTP: Support for ports 25 (forwarding), 587 (STARTTLS), and 465 (SSL)
  • IMAP Server: Support for ports 143 (no SSL) and 993 (SSL) for email retrieval
  • LMTP Server: Support for port 24 (no SSL) and 1024 (SSL) for local mail transfer
  • Mailbox Management: REST API for creating, deleting, and managing mailboxes
  • Email Sending: DNS MX lookup and external mail server delivery
  • Dynamic IP Selection: Send emails from different IP addresses based on API response
  • Queue Management: Robust email queue with retry logic and failure tracking
  • Separate Email Tables: Different collections for outgoing, successful, bounced, and incoming emails
  • MongoDB Storage: Persistent email storage with structured schemas
  • Web Dashboard: Real-time queue monitoring and management interface
  • REST API: Complete API for queue management and email status
  • Webhook Notifications: Success/failure notifications with detailed error information
  • Configuration Management: Environment-based configuration
  • Docker Support: Containerized deployment with host networking for multi-IP support
  • Logging: Centralized logging with configurable levels
  • Graceful Shutdown: Proper cleanup on application termination
  • Error Handling: Comprehensive error handling throughout the application

โ ๐Ÿ“ฆ Installation

โ Local Installation
  1. Clone the repository

  2. Install dependencies:

    npm install
    
  3. Copy the environment example and configure:

    cp env.example .env
    
  4. Update the .env file with your configuration

โ Docker Installation
  1. Clone the repository
  2. Build and run with Docker Compose:
    docker-compose up --build
    

Note: For multi-IP support, the Docker container uses network_mode: host which requires Linux. For other platforms, modify docker-compose.yml to use bridge networking.

โ โš™๏ธ Configuration

Create a .env file with the following options:

# Mailbox API Configuration
MAILBOX_API_PORT=8080
MAILBOX_API_KEY=changeme

# Server Configuration
SMTP_PORT=2525
SMTP_HOST=0.0.0.0
API_PORT=3000

# Multi-Port SMTP Configuration
SMTP_25_PORT=25
SMTP_465_PORT=465
SMTP_587_PORT=587

# LMTP Configuration
LMTP_24_PORT=24
LMTP_PORT=24
LMTP_SSL_PORT=1024
LMTP_SSL_ENABLED=false
LMTP_SSL_KEY=/path/to/lmtp-key.pem
LMTP_SSL_CERT=/path/to/lmtp-cert.pem
LMTP_SSL_CA=/path/to/lmtp-ca.pem

# IMAP Configuration
IMAP_143_PORT=143
IMAP_993_PORT=993
IMAP_PORT=143
IMAP_SSL_PORT=993
IMAP_SSL_ENABLED=false
IMAP_SSL_KEY=/path/to/imap-key.pem
IMAP_SSL_CERT=/path/to/imap-cert.pem
IMAP_SSL_CA=/path/to/imap-ca.pem

# Database Configuration
MONGODB_URL=mongodb://localhost:27017/smtp-server

# Email Configuration
MAX_EMAIL_SIZE=10485760
ALLOWED_DOMAINS=example.com,test.com

# Webhook Configuration
WEBHOOK_ENABLED=false
WEBHOOK_SUCCESS_URL=https://your-webhook-url.com/success
WEBHOOK_FAILURE_URL=https://your-webhook-url.com/failure
WEBHOOK_TIMEOUT=10000
WEBHOOK_RETRIES=3

# IP Selection Configuration
IP_SELECTION_ENABLED=false
IP_SELECTION_API_URL=https://your-ip-api.com/get-ip
IP_SELECTION_TIMEOUT=5000
IP_SELECTION_RETRIES=3
FALLBACK_IP=1.2.3.4

# Logging Configuration
LOG_LEVEL=info
ENABLE_CONSOLE_LOG=true

โ ๐Ÿƒโ€โ™‚๏ธ Running the Server

โ Local Development
npm start

Or directly:

node server.js
โ Docker Deployment
docker-compose up --build

โ ๐Ÿ“ฌ Mailbox Management API

The Mailbox API runs on port 8080 by default and provides endpoints for managing email accounts:

โ Authentication

All endpoints require the API key in the x-api-key header or api_key query parameter.

โ Endpoints
  • Create Mailbox

    POST /api/mailboxes
    Content-Type: application/json
    x-api-key: your-api-key
    
    {
      "username": "[email protected]",
      "password": "securepassword"
    }
    
  • List Mailboxes

    GET /api/mailboxes
    x-api-key: your-api-key
    
  • Delete Mailbox

    DELETE /api/mailboxes/[email protected]
    x-api-key: your-api-key
    
  • Change Password

    POST /api/mailboxes/[email protected]/change-password
    Content-Type: application/json
    x-api-key: your-api-key
    
    {
      "oldPassword": "oldpassword",
      "newPassword": "newpassword"
    }
    

โ ๐Ÿ”ง Protocol Commands Supported

โ SMTP Commands
  • HELO/EHLO - Greeting and identification
  • MAIL FROM: - Specify sender
  • RCPT TO: - Specify recipients
  • DATA - Begin email data transmission
  • QUIT - End connection
  • RSET - Reset current transaction
โ IMAP Commands
  • CAPABILITY - List server capabilities
  • LOGIN - Authenticate user
  • SELECT - Select mailbox
  • LIST - List mailboxes
  • FETCH - Retrieve message data
  • SEARCH - Search for messages
  • SORT - Sort messages by criteria
  • UID - UID-based operations
  • NOOP - Keep connection alive
  • LOGOUT - Close connection
โ LMTP Commands
  • LHLO - Greeting and identification
  • MAIL - Specify sender
  • RCPT - Specify recipients
  • DATA - Begin email data transmission
  • QUIT - End connection
  • RSET - Reset current transaction
  • NOOP - Keep connection alive

โ ๐Ÿงช Testing

โ Automated Tests
npm test                    # Test email sending
npm run test:ip            # Test IP selection
npm run test:ports         # Test multi-port SMTP
npm run test:lmtp          # Test LMTP server
โ Manual Testing
โ SMTP Testing
telnet localhost 2525
โ IMAP Testing
telnet localhost 143
โ LMTP Testing
telnet localhost 24
โ Separate Tables Testing
node test-separate-tables.js

โ ๐Ÿ“Š Monitoring

โ Web Dashboard

Access the real-time queue dashboard at: http://localhost:3000โ 

โ API Endpoints
  • GET /api/queue/stats - Get queue statistics
  • GET /api/emails - List emails with pagination
  • GET /api/emails/:id - Get specific email details
  • POST /api/emails/:id/retry - Retry failed email
  • DELETE /api/emails/:id - Delete email
  • GET /api/successful-emails - List successfully delivered emails
  • GET /api/successful-emails/:id - Get specific successful email details
  • GET /api/bounced-emails - List bounced emails
  • GET /api/bounced-emails/:id - Get specific bounced email details
  • GET /api/incoming-emails - List incoming emails
  • GET /api/incoming-emails/:id - Get specific incoming email details
  • DELETE /api/incoming-emails/:id - Delete incoming email
  • GET /api/email-stats - Get comprehensive email statistics
  • GET /api/ip-selection/stats - Get IP selection cache statistics
  • POST /api/ip-selection/clear-cache - Clear IP selection cache
  • POST /api/ip-selection/test - Test IP selection for specific email
  • GET /api/smtp/stats - Get multi-port SMTP server statistics
  • GET /api/imap/stats - Get IMAP server statistics
  • GET /api/lmtp/stats - Get LMTP server statistics
  • GET /health - Health check

โ ๐Ÿณ Docker Deployment

โ Multi-IP Support

For applications requiring multiple source IPs (e.g., email sending from different IPs), the Docker container uses network_mode: host. This allows the container to bind to all host network interfaces and send traffic from any available source IP.

โ Standard Deployment
# Build and start all services
docker-compose up --build

# Run in background
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down
โ Custom Ports

Modify the docker-compose.yml file to change default ports or use bridge networking instead of host networking.

โ ๐Ÿ“‹ Module Documentation

โ Config Module (config/)
โ config.js

Centralized configuration management that loads environment variables and provides defaults.

โ database.js

Database connection management with connection pooling and error handling.

โ Models Module (models/)
โ Email.js

MongoDB schema for outgoing email storage including:

  • Sender and recipient information
  • Subject, text, and HTML content
  • Attachments with metadata
  • Raw email data
  • Queue management fields (status, retry count, attempts)
  • References to successful and bounced email records
  • Timestamps
โ SuccessfulEmail.js

MongoDB schema for successfully delivered emails including:

  • Reference to original email
  • Delivery confirmation details
  • SMTP response information
  • Delivery timestamp
โ BouncedEmail.js

MongoDB schema for bounced/failed emails including:

  • Reference to original email
  • Bounce type (hard, soft, transient, permanent)
  • Bounce reason and error codes
  • Bounce timestamp
โ IncomingEmail.js

MongoDB schema for incoming emails including:

  • Sender and recipient information
  • Source tracking (SMTP, IMAP, LMTP)
  • Message headers and metadata
  • Processing status
  • Received timestamp
โ Mailbox.js

MongoDB schema for mailbox management including:

  • Username and hashed password
  • Creation timestamp
  • Password comparison methods
โ Services Module (services/)
โ MultiPortSMTPServer.js

Multi-port SMTP server:

  • Support for ports 25, 465, and 587
  • SSL/TLS support for secure connections
  • Port 25 forwarding to external SMTP servers
  • STARTTLS support for port 587
โ IMAPServer.js

IMAP server for email retrieval:

  • Support for ports 143 (no SSL) and 993 (SSL)
  • Modular command handlers
  • Database integration for email storage
  • SSL/TLS support for secure connections
โ LMTPServer.js

LMTP server for local mail transfer:

  • Support for port 24 (no SSL) and 1024 (SSL)
  • LMTP protocol implementation (LHLO, MAIL, RCPT, DATA, QUIT)
  • Database integration for email storage
  • SSL/TLS support for secure connections
โ EmailProcessor.js

Business logic for email processing:

  • Email validation
  • MIME parsing
  • Queue management
  • Error handling
โ MailSender.js

Handles external email delivery:

  • DNS MX record lookup
  • SMTP client for external servers
  • Connection management and timeout handling
  • Error handling and retry logic
โ EmailQueue.js

Queue management system:

  • Email queuing and processing
  • Retry logic with exponential backoff
  • Failure tracking and permanent failure handling
  • Queue statistics and monitoring
โ QueueAPI.js

Web interface and API:

  • REST API for queue management
  • Real-time dashboard
  • Email status monitoring
  • Manual retry functionality
  • IP selection management
โ MailboxAPI.js

Mailbox management API:

  • REST API for mailbox operations
  • API key authentication
  • Create, delete, and manage mailboxes
  • Password change functionality
โ IPSelectionService.js

Dynamic IP selection:

  • API-based IP selection for email sending
  • Caching mechanism for performance
  • Fallback IP support
  • Retry logic for API failures
โ IMAP Commands Module (services/imap/commands/)
โ CapabilityCommand.js

Handles IMAP CAPABILITY command:

  • Lists server capabilities
  • Supports SORT, THREAD, and other extensions
โ LoginCommand.js

Handles IMAP LOGIN command:

  • User authentication
  • State management
โ SelectCommand.js

Handles IMAP SELECT command:

  • Mailbox selection
  • Status information
โ FetchCommand.js

Handles IMAP FETCH command:

  • Message data retrieval
  • Multiple data item support
โ SearchCommand.js

Handles IMAP SEARCH command:

  • Message searching
  • Multiple search criteria
โ SortCommand.js

Handles IMAP SORT command:

  • Message sorting by various criteria
  • Combined search and sort
โ UIDCommand.js

Handles IMAP UID commands:

  • UID-based operations
  • FETCH, SEARCH, SORT, STORE
โ Utils Module (utils/)
โ logger.js

Centralized logging system with:

  • Configurable log levels
  • Timestamp formatting
  • Console output control
  • Structured logging

โ ๐Ÿ“Š Email Storage

Emails are stored in MongoDB with the following structure:

{
  sender: String,
  recipients: [String],
  subject: String,
  text: String,
  html: String,
  attachments: [{
    filename: String,
    contentType: String,
    content: Buffer
  }],
  raw: String,
  createdAt: Date
}

โ ๐Ÿ›ก๏ธ Error Handling

The application includes comprehensive error handling:

  • Database connection failures
  • Email processing errors
  • Protocol errors (SMTP, IMAP, LMTP)
  • Graceful shutdown on system signals
  • Uncaught exception handling

โ ๐Ÿ”„ Graceful Shutdown

The server handles graceful shutdown on:

  • SIGTERM (Docker/Kubernetes)
  • SIGINT (Ctrl+C)
  • Uncaught exceptions
  • Unhandled promise rejections

โ ๐Ÿ“ License

ISC License

Tag summary

Content type

Image

Digest

sha256:66d69e4d5โ€ฆ

Size

61.2 MB

Last updated

about 1 year ago

docker pull kunalghoshone/imap-smtp