Skip to content

API Integration

Integrating Mailborder with external systems using the REST API.

API Overview

API Architecture

Base URL:

https://your-mailborder-server.com/api/v1/

Authentication: - Bearer token authentication - API key authentication - Session-based authentication

Response Format: - JSON responses - Standard HTTP status codes - Consistent error format

Rate Limiting: - 1000 requests per hour per API key - 10000 requests per hour for admin keys

Authentication

Generate API Key

Via web interface: 1. Navigate to Profile → API Keys 2. Click "Generate New API Key" 3. Set permissions and expiration 4. Save securely (displayed only once)

Via CLI:

sudo mb-api-key-create --user admin@example.com --permissions read,write --expires 90d

Output:

API Key: mbkey_a1b2c3d4e5f6g7h8i9j0
Permissions: read,write
Expires: 2026-02-12

Authentication Methods

Bearer Token:

curl -H "Authorization: Bearer mbkey_a1b2c3d4e5f6g7h8i9j0" \
  https://mailborder.example.com/api/v1/status

API Key Header:

curl -H "X-API-Key: mbkey_a1b2c3d4e5f6g7h8i9j0" \
  https://mailborder.example.com/api/v1/status

Session Cookie:

# Login first
curl -c cookies.txt -d '{"email":"admin@example.com","password":"secret"}' \
  https://mailborder.example.com/api/v1/auth/login

# Use session
curl -b cookies.txt https://mailborder.example.com/api/v1/status

API Endpoints

System Status

GET /api/v1/status

Get system status and health.

curl -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/status

Response:

{
  "status": "healthy",
  "version": "6.0.0",
  "uptime": 86400,
  "services": {
    "mb-rpcd": "active",
    "mb-filter": "active",
    "database": "connected",
    "redis": "connected"
  },
  "queue": {
    "active": 5,
    "deferred": 2,
    "total": 7
  },
  "timestamp": "2025-11-12T15:30:00Z"
}

Email Statistics

GET /api/v1/stats

Get email processing statistics.

Parameters: - period - Time period: hour, day, week, month (default: day) - start - Start date (ISO 8601) - end - End date (ISO 8601)

curl -H "Authorization: Bearer $API_KEY" \
  "https://mailborder.example.com/api/v1/stats?period=day"

Response:

{
  "period": "day",
  "start": "2025-11-12T00:00:00Z",
  "end": "2025-11-12T23:59:59Z",
  "total_processed": 15234,
  "clean": 12456,
  "spam": 2145,
  "virus": 23,
  "rejected": 610,
  "quarantined": 2168,
  "avg_processing_time_ms": 45.2
}

Quarantine Management

GET /api/v1/quarantine

List quarantined emails.

Parameters: - limit - Number of results (default: 100, max: 1000) - offset - Pagination offset - recipient - Filter by recipient - sender - Filter by sender - since - Start date - until - End date

curl -H "Authorization: Bearer $API_KEY" \
  "https://mailborder.example.com/api/v1/quarantine?limit=10&recipient=user@example.com"

Response:

{
  "total": 145,
  "offset": 0,
  "limit": 10,
  "quarantine": [
    {
      "id": "q12345",
      "from": "sender@example.com",
      "to": "user@example.com",
      "subject": "Special Offer",
      "date": "2025-11-12T14:23:45Z",
      "reason": "spam",
      "score": 8.5,
      "size": 45234
    }
  ]
}

GET /api/v1/quarantine/{id}

Get quarantine email details.

curl -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/quarantine/q12345

POST /api/v1/quarantine/{id}/release

Release quarantined email.

curl -X POST -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/quarantine/q12345/release

Response:

{
  "success": true,
  "message": "Email released and delivered",
  "id": "q12345"
}

DELETE /api/v1/quarantine/{id}

Delete quarantined email.

curl -X DELETE -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/quarantine/q12345

Whitelist/Blacklist Management

GET /api/v1/whitelist

List whitelist entries.

curl -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/whitelist

POST /api/v1/whitelist

Add whitelist entry.

curl -X POST -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type":"sender","value":"trusted@example.com","comment":"Partner domain"}' \
  https://mailborder.example.com/api/v1/whitelist

DELETE /api/v1/whitelist/{id}

Remove whitelist entry.

curl -X DELETE -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/whitelist/123

GET /api/v1/blacklist

List blacklist entries.

POST /api/v1/blacklist

Add blacklist entry.

curl -X POST -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type":"sender","value":"spam@example.com","comment":"Known spammer"}' \
  https://mailborder.example.com/api/v1/blacklist

User Management

GET /api/v1/users

List users.

curl -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/users

POST /api/v1/users

Create user.

curl -X POST -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "newuser@example.com",
    "password": "secure_password",
    "display_name": "New User",
    "privilege_level": 5
  }' \
  https://mailborder.example.com/api/v1/users

PUT /api/v1/users/{id}

Update user.

curl -X PUT -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"privilege_level": 3}' \
  https://mailborder.example.com/api/v1/users/123

DELETE /api/v1/users/{id}

Delete user.

curl -X DELETE -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/users/123

GET /api/v1/logs

Search logs.

Parameters: - query - Search term - level - Log level: debug, info, warning, error - since - Start time - until - End time - limit - Number of results

curl -H "Authorization: Bearer $API_KEY" \
  "https://mailborder.example.com/api/v1/logs?query=spam&level=warning&limit=50"

Configuration Management

GET /api/v1/config

Get configuration.

curl -H "Authorization: Bearer $API_KEY" \
  https://mailborder.example.com/api/v1/config

PUT /api/v1/config

Update configuration.

curl -X PUT -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"spam_threshold": 6.0}' \
  https://mailborder.example.com/api/v1/config

Integration Examples

Python Integration

Install requests library:

pip install requests

Example client:

#!/usr/bin/env python3
import requests
import json

class MailborderAPI:
    def __init__(self, base_url, api_key):
        self.base_url = base_url
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }

    def get_status(self):
        """Get system status"""
        response = requests.get(
            f'{self.base_url}/api/v1/status',
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

    def get_quarantine(self, limit=100, recipient=None):
        """List quarantined emails"""
        params = {'limit': limit}
        if recipient:
            params['recipient'] = recipient

        response = requests.get(
            f'{self.base_url}/api/v1/quarantine',
            headers=self.headers,
            params=params
        )
        response.raise_for_status()
        return response.json()

    def release_quarantine(self, quarantine_id):
        """Release quarantined email"""
        response = requests.post(
            f'{self.base_url}/api/v1/quarantine/{quarantine_id}/release',
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

    def add_whitelist(self, value, list_type='sender', comment=''):
        """Add to whitelist"""
        data = {
            'type': list_type,
            'value': value,
            'comment': comment
        }
        response = requests.post(
            f'{self.base_url}/api/v1/whitelist',
            headers=self.headers,
            json=data
        )
        response.raise_for_status()
        return response.json()

    def get_stats(self, period='day'):
        """Get statistics"""
        response = requests.get(
            f'{self.base_url}/api/v1/stats',
            headers=self.headers,
            params={'period': period}
        )
        response.raise_for_status()
        return response.json()

# Usage
if __name__ == '__main__':
    api = MailborderAPI(
        base_url='https://mailborder.example.com',
        api_key='mbkey_a1b2c3d4e5f6g7h8i9j0'
    )

    # Get status
    status = api.get_status()
    print(f"Status: {status['status']}")
    print(f"Queue: {status['queue']['total']} messages")

    # Get quarantine
    quarantine = api.get_quarantine(limit=10)
    print(f"\nQuarantine: {quarantine['total']} emails")

    # Get stats
    stats = api.get_stats(period='day')
    print(f"\nProcessed today: {stats['total_processed']}")
    print(f"Spam detected: {stats['spam']}")

Node.js Integration

Install axios:

npm install axios

Example client:

const axios = require('axios');

class MailborderAPI {
    constructor(baseURL, apiKey) {
        this.client = axios.create({
            baseURL: baseURL,
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });
    }

    async getStatus() {
        const response = await this.client.get('/api/v1/status');
        return response.data;
    }

    async getQuarantine(limit = 100, recipient = null) {
        const params = { limit };
        if (recipient) params.recipient = recipient;

        const response = await this.client.get('/api/v1/quarantine', { params });
        return response.data;
    }

    async releaseQuarantine(id) {
        const response = await this.client.post(`/api/v1/quarantine/${id}/release`);
        return response.data;
    }

    async addWhitelist(value, type = 'sender', comment = '') {
        const response = await this.client.post('/api/v1/whitelist', {
            type,
            value,
            comment
        });
        return response.data;
    }

    async getStats(period = 'day') {
        const response = await this.client.get('/api/v1/stats', {
            params: { period }
        });
        return response.data;
    }
}

// Usage
(async () => {
    const api = new MailborderAPI(
        'https://mailborder.example.com',
        'mbkey_a1b2c3d4e5f6g7h8i9j0'
    );

    try {
        const status = await api.getStatus();
        console.log(`Status: ${status.status}`);
        console.log(`Queue: ${status.queue.total} messages`);

        const stats = await api.getStats('day');
        console.log(`Processed today: ${stats.total_processed}`);
        console.log(`Spam detected: ${stats.spam}`);
    } catch (error) {
        console.error('API Error:', error.response?.data || error.message);
    }
})();

PHP Integration

Example client:

<?php

class MailborderAPI {
    private $baseUrl;
    private $apiKey;

    public function __construct($baseUrl, $apiKey) {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiKey = $apiKey;
    }

    private function request($method, $endpoint, $data = null) {
        $ch = curl_init();

        $url = $this->baseUrl . $endpoint;
        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ];

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        } elseif ($method === 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        } elseif ($method === 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 400) {
            throw new Exception("API Error: HTTP $httpCode");
        }

        return json_decode($response, true);
    }

    public function getStatus() {
        return $this->request('GET', '/api/v1/status');
    }

    public function getQuarantine($limit = 100, $recipient = null) {
        $endpoint = '/api/v1/quarantine?limit=' . $limit;
        if ($recipient) {
            $endpoint .= '&recipient=' . urlencode($recipient);
        }
        return $this->request('GET', $endpoint);
    }

    public function releaseQuarantine($id) {
        return $this->request('POST', "/api/v1/quarantine/$id/release");
    }

    public function addWhitelist($value, $type = 'sender', $comment = '') {
        return $this->request('POST', '/api/v1/whitelist', [
            'type' => $type,
            'value' => $value,
            'comment' => $comment
        ]);
    }

    public function getStats($period = 'day') {
        return $this->request('GET', "/api/v1/stats?period=$period");
    }
}

// Usage
$api = new MailborderAPI(
    'https://mailborder.example.com',
    'mbkey_a1b2c3d4e5f6g7h8i9j0'
);

try {
    $status = $api->getStatus();
    echo "Status: " . $status['status'] . "\n";
    echo "Queue: " . $status['queue']['total'] . " messages\n";

    $stats = $api->getStats('day');
    echo "Processed today: " . $stats['total_processed'] . "\n";
    echo "Spam detected: " . $stats['spam'] . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Webhooks

Configure Webhooks

Add webhook endpoint:

curl -X POST -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/mailborder",
    "events": ["quarantine.new", "virus.detected", "spam.high_score"],
    "secret": "your_webhook_secret"
  }' \
  https://mailborder.example.com/api/v1/webhooks

Webhook Events

Available events: - quarantine.new - New email quarantined - quarantine.released - Email released from quarantine - virus.detected - Virus detected - spam.high_score - High spam score - user.login - User login - user.failed_login - Failed login attempt - config.changed - Configuration changed

Webhook payload example:

{
  "event": "quarantine.new",
  "timestamp": "2025-11-12T15:30:00Z",
  "data": {
    "id": "q12345",
    "from": "sender@example.com",
    "to": "user@example.com",
    "subject": "Suspicious Email",
    "reason": "spam",
    "score": 8.5
  },
  "signature": "sha256_hmac_signature"
}

Verify webhook signature (Python):

import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)

Rate Limiting

Rate limit headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1699887600

Handle rate limits:

import time

def api_call_with_retry(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:  # Too Many Requests
                retry_after = int(e.response.headers.get('Retry-After', 60))
                time.sleep(retry_after)
            else:
                raise
    raise Exception("Max retries exceeded")

Error Handling

Standard error response:

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Invalid quarantine ID",
    "details": {
      "field": "id",
      "reason": "not_found"
    }
  }
}

Error codes: - INVALID_REQUEST - Invalid request parameters - UNAUTHORIZED - Authentication failed - FORBIDDEN - Insufficient permissions - NOT_FOUND - Resource not found - RATE_LIMIT_EXCEEDED - Too many requests - INTERNAL_ERROR - Server error

Best Practices

Security: - Store API keys securely (environment variables, secrets manager) - Use HTTPS only - Rotate API keys regularly - Implement webhook signature verification - Use minimum required permissions

Performance: - Implement connection pooling - Use pagination for large result sets - Cache responses when appropriate - Handle rate limits gracefully - Use batch operations when available

Reliability: - Implement retry logic with exponential backoff - Log all API interactions - Monitor API usage - Set appropriate timeouts - Handle errors gracefully

See Also