<\!DOCTYPE html> API Overview

API Overview

Mail-Rulez provides a RESTful API for programmatic access to email management functionality. This enables integration with external systems, automation tools, and custom applications.

API Endpoints

The API is available at https://your-domain.com/api/v1/

Authentication

All API requests require authentication using session cookies or API tokens.

# Login to get session cookie
curl -X POST https://your-domain.com/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "your-password"}' \
  -c cookies.txt

# Use session cookie for subsequent requests
curl -X GET https://your-domain.com/api/v1/accounts \
  -b cookies.txt

Core Endpoints

Accounts Management

List All Accounts

GET /api/v1/accounts

Response:

{
  "accounts": [
    {
      "id": 1,
      "email": "[email protected]",
      "server": "imap.gmail.com",
      "status": "connected",
      "last_sync": "2024-01-15T10:30:00Z",
      "folder_count": 12,
      "message_count": 1543
    }
  ]
}

Get Account Details

GET /api/v1/accounts/{account_id}

Add New Account

POST /api/v1/accounts
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "app-specific-password",
  "server": "imap.gmail.com",
  "port": 993,
  "use_ssl": true
}

Update Account

PUT /api/v1/accounts/{account_id}
Content-Type: application/json

{
  "password": "new-app-password",
  "active": true
}

Delete Account

DELETE /api/v1/accounts/{account_id}

Rules Management

List Rules

GET /api/v1/rules

Response:

{
  "rules": [
    {
      "id": 1,
      "name": "Invoice Processing",
      "priority": 10,
      "active": true,
      "conditions": {
        "subject_contains": ["invoice", "receipt"],
        "match_type": "any"
      },
      "actions": {
        "move_to": "Receipts",
        "mark_as_read": true
      },
      "stats": {
        "matches_today": 15,
        "total_matches": 342
      }
    }
  ]
}

Create Rule

POST /api/v1/rules
Content-Type: application/json

{
  "name": "Newsletter Filter",
  "priority": 20,
  "conditions": {
    "from_contains": ["newsletter", "noreply"],
    "subject_contains": ["unsubscribe"],
    "match_type": "all"
  },
  "actions": {
    "move_to": "Newsletters",
    "mark_as_read": true
  }
}

Test Rule

POST /api/v1/rules/test
Content-Type: application/json

{
  "rule_id": 1,
  "sample_count": 10
}

Response shows which emails would be matched:

{
  "matches": [
    {
      "subject": "Invoice #12345",
      "from": "[email protected]",
      "date": "2024-01-15T09:15:00Z",
      "would_move_to": "Receipts"
    }
  ],
  "match_count": 3,
  "sample_size": 10
}

Lists Management

Get Lists

GET /api/v1/lists

Response:

{
  "whitelist": ["[email protected]", "*@trustedcompany.com"],
  "blacklist": ["[email protected]", "*@spamdomain.com"],
  "vendorlist": ["[email protected]", "*@shopping.com"]
}

Add to List

POST /api/v1/lists/{list_type}/add
Content-Type: application/json

{
  "entries": ["[email protected]", "*@domain.com"]
}

Remove from List

POST /api/v1/lists/{list_type}/remove
Content-Type: application/json

{
  "entries": ["[email protected]"]
}

Bulk Import

POST /api/v1/lists/{list_type}/import
Content-Type: text/plain

[email protected]
[email protected]
*@pattern.com

Processing Control

Get Processing Status

GET /api/v1/processing/status

Response:

{
  "status": "running",
  "mode": "maintenance",
  "last_run": "2024-01-15T10:45:00Z",
  "emails_processed_today": 523,
  "next_run": "2024-01-15T11:00:00Z",
  "queue_size": 0
}

Start Processing

POST /api/v1/processing/start
Content-Type: application/json

{
  "mode": "startup",
  "batch_size": 100,
  "account_id": 1  // optional, process specific account
}

Stop Processing

POST /api/v1/processing/stop

Process Next Batch

POST /api/v1/processing/next-batch
Content-Type: application/json

{
  "batch_size": 100,
  "dry_run": false
}

Retention Management

Get Retention Policies

GET /api/v1/retention/policies

Create Retention Policy

POST /api/v1/retention/policies
Content-Type: application/json

{
  "name": "Old Newsletters",
  "type": "folder",
  "folder_pattern": "Newsletters/*",
  "retention_days": 30,
  "active": true
}

Execute Retention

POST /api/v1/retention/execute
Content-Type: application/json

{
  "policy_id": 1,
  "dry_run": true  // Preview what would be deleted
}

Statistics and Monitoring

Get Dashboard Stats

GET /api/v1/stats/dashboard

Response:

{
  "system": {
    "cpu_percent": 15.2,
    "memory_percent": 42.5,
    "disk_usage_gb": 3.2,
    "uptime_hours": 168
  },
  "email": {
    "total_accounts": 3,
    "total_emails": 15234,
    "processed_today": 523,
    "processing_rate": 8.7  // emails per minute
  },
  "rules": {
    "total": 15,
    "active": 12,
    "matches_today": 387
  }
}

Get Processing History

GET /api/v1/stats/history?days=7

Export Logs

GET /api/v1/logs/export?type=processing&format=json&date=2024-01-15

Webhooks

Configure webhooks for real-time notifications:

POST /api/v1/webhooks
Content-Type: application/json

{
  "url": "https://your-app.com/webhook",
  "events": ["processing.completed", "rule.matched", "error.occurred"],
  "secret": "your-webhook-secret"
}

Webhook payload example:

{
  "event": "processing.completed",
  "timestamp": "2024-01-15T11:00:00Z",
  "data": {
    "account_id": 1,
    "emails_processed": 100,
    "duration_seconds": 45,
    "rules_matched": 73
  }
}

Error Handling

All API endpoints return consistent error responses:

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Account not found",
    "details": {
      "account_id": 999
    }
  }
}

Common error codes:

  • UNAUTHORIZED - Authentication required
  • FORBIDDEN - Insufficient permissions
  • NOT_FOUND - Resource not found
  • INVALID_REQUEST - Bad request parameters
  • RATE_LIMITED - Too many requests
  • SERVER_ERROR - Internal server error

Rate Limiting

API requests are rate-limited to prevent abuse:

  • 100 requests per minute for read operations
  • 20 requests per minute for write operations
  • 5 requests per minute for processing operations

Rate limit headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705320000

Code Examples

Python

import requests

class MailRulezAPI:
    def __init__(self, base_url, username, password):
        self.base_url = base_url
        self.session = requests.Session()
        self.login(username, password)
    
    def login(self, username, password):
        response = self.session.post(
            f"{self.base_url}/auth/login",
            json={"username": username, "password": password}
        )
        response.raise_for_status()
    
    def get_accounts(self):
        response = self.session.get(f"{self.base_url}/api/v1/accounts")
        response.raise_for_status()
        return response.json()
    
    def create_rule(self, rule_data):
        response = self.session.post(
            f"{self.base_url}/api/v1/rules",
            json=rule_data
        )
        response.raise_for_status()
        return response.json()

# Usage
api = MailRulezAPI("https://mail-rulez.example.com", "admin", "password")
accounts = api.get_accounts()

JavaScript

class MailRulezAPI {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }
  
  async login(username, password) {
    const response = await fetch(`${this.baseUrl}/auth/login`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      credentials: 'include',
      body: JSON.stringify({username, password})
    });
    
    if (!response.ok) throw new Error('Login failed');
  }
  
  async getAccounts() {
    const response = await fetch(`${this.baseUrl}/api/v1/accounts`, {
      credentials: 'include'
    });
    
    if (!response.ok) throw new Error('Failed to fetch accounts');
    return response.json();
  }
  
  async processNextBatch(batchSize = 100) {
    const response = await fetch(`${this.baseUrl}/api/v1/processing/next-batch`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      credentials: 'include',
      body: JSON.stringify({batch_size: batchSize})
    });
    
    if (!response.ok) throw new Error('Processing failed');
    return response.json();
  }
}

// Usage
const api = new MailRulezAPI('https://mail-rulez.example.com');
await api.login('admin', 'password');
const accounts = await api.getAccounts();

cURL Script

#!/bin/bash
# mail-rulez-api.sh

BASE_URL="https://mail-rulez.example.com"
COOKIE_JAR="/tmp/mail-rulez-cookies.txt"

# Login function
login() {
    curl -s -X POST "$BASE_URL/auth/login" \
        -H "Content-Type: application/json" \
        -d "{\"username\": \"$1\", \"password\": \"$2\"}" \
        -c "$COOKIE_JAR"
}

# API request function
api_request() {
    local method=$1
    local endpoint=$2
    local data=$3
    
    curl -s -X "$method" "$BASE_URL/api/v1/$endpoint" \
        -H "Content-Type: application/json" \
        -b "$COOKIE_JAR" \
        ${data:+-d "$data"}
}

# Usage examples
login "admin" "password"
api_request GET "accounts" | jq '.'
api_request POST "processing/start" '{"mode": "maintenance"}'

API Clients

Official and community API clients:

  • Python: pip install mail-rulez-client (coming soon)
  • Node.js: npm install @mail-rulez/client (coming soon)
  • Go: go get github.com/Real-PM/mail-rulez-go (coming soon)

Best Practices

  1. Authentication

    • Use API tokens for automation
    • Rotate credentials regularly
    • Never expose credentials in logs
  2. Error Handling

    • Implement exponential backoff for retries
    • Log all errors with context
    • Handle rate limits gracefully
  3. Performance

    • Cache frequently accessed data
    • Use batch operations where available
    • Implement request pooling
  4. Security

    • Always use HTTPS
    • Validate webhook signatures
    • Implement request timeouts

Related Documentation