# MailCatcher NG full reference > MailCatcher NG is a development SMTP server that catches email and displays it in a web interface. [Documentation index](https://spaquet.github.io/mailcatcher/llms.txt) --- # Installation ## Quick Start 1. `gem install mailcatcher-ng` 2. `mailcatcher` 3. Go to http://127.0.0.1:1080/ 4. Send mail through smtp://127.0.0.1:1025 ## Docker The official MailCatcher Docker image is available [on Docker Hub](https://hub.docker.com/r/stpaquet/alpinemailcatcher): ```bash docker run -d -p 1080:1080 -p 1025:1025 stpaquet/alpinemailcatcher ``` Example output: ``` Unable to find image 'stpaquet/alpinemailcatcher:latest' locally latest: Pulling from stpaquet/alpinemailcatcher 4abcf2090661: Pull complete 9f403268fa96: Pull complete 6c9f5f5b4c6d: Pull complete Digest: sha256:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0 Status: Downloaded newer image for stpaquet/alpinemailcatcher:latest Starting MailCatcher NG v1.0.0 ==> smtp://0.0.0.0:1025 ==> http://0.0.0.0:1080 ``` Port mapping may vary based on your Docker configuration. For example, you may need to use `http://127.0.0.1:1080` or `smtp://127.0.0.1:1025` instead of the listed address. The image is Alpine Linux based for minimal size and quick startup. ## Requirements ### Ruby Make sure you have [Ruby installed](https://www.ruby-lang.org/en/documentation/installation/): ```bash ruby -v gem environment ``` You might need to install build tools for some of the gem dependencies: - **Debian/Ubuntu**: `apt install build-essential` - **macOS**: `xcode-select --install` ## Installation Methods ### Using gem (Recommended) ```bash gem install mailcatcher-ng ``` ### From Source To compile MailCatcher as a gem from source: 1. Clone the repository: ```bash git clone https://github.com/spaquet/mailcatcher.git cd mailcatcher ``` 2. Install dependencies: ```bash bundle install ``` 3. Compile assets and build the gem: ```bash bundle exec rake package ``` This will create a `.gem` file in the project directory. The build process: * Compiles JavaScript assets using Sprockets and Uglifier * Creates a gem package with all required files 4. Install the compiled gem locally: ```bash gem install mailcatcher-VERSION.gem ``` ## Upgrading Upgrading works the same as installation: ```bash gem install mailcatcher-ng ``` ## Special Setup Scenarios ### Bundler Please don't put mailcatcher into your Gemfile. It will conflict with your application's gems at some point. Instead, add a note in your README stating you use mailcatcher, and instruct users to run: ```bash gem install mailcatcher-ng mailcatcher ``` ### RVM Under RVM your mailcatcher command may only be available under the ruby you install mailcatcher into. To prevent this and to prevent gem conflicts, install mailcatcher into a dedicated gemset with a wrapper script: ```bash rvm default@mailcatcher --create do gem install mailcatcher-ng ln -s "$(rvm default@mailcatcher do rvm wrapper show mailcatcher)" "$rvm_bin_path/" ``` --- # Usage ## Running MailCatcher NG ### Basic Usage ```bash mailcatcher ``` Then visit [http://127.0.0.1:1080](http://127.0.0.1:1080) and send mail to `smtp://127.0.0.1:1025`. ### Command Line Options Use `mailcatcher --help` to see all available options: ``` Usage: mailcatcher [options] MailCatcher NG v1.5.2 --ip IP Set the ip address of both servers --smtp-ip IP Set the ip address of the smtp server --smtp-port PORT Set the port of the smtp server --smtp-ssl Enable SSL/TLS support for SMTP --smtp-ssl-cert PATH Path to SSL certificate file --smtp-ssl-key PATH Path to SSL private key file --smtp-ssl-verify-peer Verify client SSL certificates --smtps-port PORT Set the port for direct TLS (default: 1465) --http-ip IP Set the ip address of the http server --http-port PORT Set the port address of the http server --messages-limit COUNT Only keep up to COUNT most recent messages --persistence Store messages in a persistent SQLite database file --http-path PATH Add a prefix to all HTTP paths --forward-smtp-host HOST SMTP server for forwarding messages --forward-smtp-port PORT SMTP port for forwarding messages --forward-smtp-user USER SMTP username for forwarding messages --forward-smtp-password PASS SMTP password for forwarding messages --[no-]forward-smtp-tls Enable/disable TLS for forwarding SMTP (default: enabled) --mcp Enable MCP server for Claude integration --plugin Enable Claude Plugin endpoints --no-quit Don't allow quitting the process -f, --foreground Run in the foreground -b, --browse Open web browser -v, --verbose Be more verbose -h, --help Display this help information --version Display the current version ``` ## Message Forwarding Forward caught email messages to real SMTP servers for validation before production deployment: ```bash mailcatcher \ --forward-smtp-host smtp.example.com \ --forward-smtp-port 587 \ --forward-smtp-user your-username@example.com \ --forward-smtp-password your-password ``` Then use the `/messages/:id/forward` API endpoint to forward specific messages. See [API documentation](https://github.com/spaquet/mailcatcher/blob/main/reference/API.md) for details. ## Claude Integration ### Claude Plugin Enable the Claude Plugin for use in Claude.com or Claude Desktop: ```bash mailcatcher --plugin --foreground ``` Then add the plugin in Claude: 1. Go to Claude settings/plugins 2. Click "Create a plugin" 3. Enter: `http://localhost:1080/.well-known/ai-plugin.json` 4. Click Install Claude now has access to email search, token extraction, and message management tools. ### MCP Server Enable the MCP (Model Context Protocol) server for programmatic access: ```bash mailcatcher --mcp --foreground ``` Configure Claude Desktop by editing `~/.claude_desktop_config.json`: ```json { "mcpServers": { "mailcatcher": { "command": "mailcatcher", "args": ["--mcp", "--foreground"] } } } ``` Then restart Claude Desktop to enable MCP tools. ### Both Plugin and MCP For maximum flexibility, enable both: ```bash mailcatcher --mcp --plugin --foreground ``` For complete setup guides, see [Claude Plugin Setup](https://github.com/spaquet/mailcatcher/blob/main/reference/CLAUDE_PLUGIN_SETUP.md) and [MCP Setup](https://github.com/spaquet/mailcatcher/blob/main/reference/MCP_SETUP.md). ## Development Mode Run MailCatcher NG in development mode with custom ports: ```bash MAILCATCHER_ENV=development bundle exec mailcatcher --foreground --smtp-port 1025 --http-port 1080 ``` Then access the web interface at [http://127.0.0.1:1080](http://127.0.0.1:1080) and send mail to `smtp://127.0.0.1:1025`. ### Sending Example Emails Use the provided test script to send example emails: ```bash SMTP_HOST=127.0.0.1 SMTP_PORT=20025 ruby send_example_emails.rb ``` ## Web Interface ### Features - View HTML, plain text, and source versions of messages - Download original email to view in your native mail client - List attachments and download individual parts - HTML rewriting for embedded images and safe link opening ### Real-time Updates Mail appears instantly if your browser supports [WebSockets](https://tools.ietf.org/html/rfc6455) with automatic reconnection and exponential backoff. Otherwise, updates refresh every thirty seconds. ### WebSocket Testing To monitor WebSocket connectivity and test the connection status, visit [http://127.0.0.1:1080/websocket-test](http://127.0.0.1:1080/websocket-test). This page provides real-time feedback on WebSocket connection state and helps verify that automatic reconnection with exponential backoff is functioning correctly. ### Keyboard Navigation Use keyboard shortcuts to navigate between messages in the web interface. ## Background Operation MailCatcher NG runs as a daemon in the background by default. To run in the foreground instead: ```bash mailcatcher --foreground ``` ### Browser Integration Open your default web browser automatically on startup: ```bash mailcatcher --browse ``` ## Limiting Messages To prevent excessive memory usage, limit the number of messages stored: ```bash mailcatcher --messages-limit 100 ``` Only the 100 most recent messages will be kept. ## Persistent Storage By default, MailCatcher NG stores messages in memory and they are lost when the process terminates. To keep messages across restarts, enable persistent storage: ```bash mailcatcher --persistence ``` Messages will be stored in a SQLite database file at `~/.mailcatcher/mailcatcher.db`. The directory is automatically created if it doesn't exist. You can combine persistence with other options: ```bash mailcatcher --persistence --messages-limit 500 ``` ## Custom HTTP Path Add a prefix to all HTTP paths (useful when running behind a reverse proxy): ```bash mailcatcher --http-path /mailcatcher ``` Access the web interface at `http://127.0.0.1:1080/mailcatcher/` --- # Advanced Features ## SSL/TLS Support MailCatcher NG supports both STARTTLS and direct TLS (SMTPS) for encrypted SMTP connections. This is useful for testing email delivery in staging environments that require secure connections. ### Generate a Self-Signed Certificate For testing purposes, create a self-signed certificate: ```bash openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes ``` This creates: - `cert.pem`: Certificate file - `key.pem`: Private key file ### Start MailCatcher NG with SSL/TLS ```bash mailcatcher --smtp-ssl --smtp-ssl-cert cert.pem --smtp-ssl-key key.pem ``` ### Connection Methods This enables two connection methods: - **STARTTLS on port 1025**: Plain connections that upgrade via STARTTLS command (required) - **Direct TLS on port 1465**: Encrypted connections from the start (SMTPS) **Important:** When SSL/TLS is enabled, STARTTLS is required before sending mail. Clients must complete the TLS upgrade first. ### Client Certificate Verification (Optional) Enable verification of client SSL certificates (mutual TLS): ```bash mailcatcher --smtp-ssl --smtp-ssl-cert cert.pem --smtp-ssl-key key.pem --smtp-ssl-verify-peer ``` ### Framework Configuration #### Rails with STARTTLS ```ruby config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1025, enable_starttls_auto: true } ``` #### Django with TLS Direct TLS (SMTPS) on port 1465: ```python if DEBUG: EMAIL_HOST = '127.0.0.1' EMAIL_PORT = 1465 # Direct TLS EMAIL_USE_TLS = True EMAIL_USE_SSL = True ``` ### Security Considerations - **Self-signed certificates**: Will trigger warnings in mail clients but work for development - **Production certificates**: Use proper certificates for staging environments - **Certificate validation**: Mail clients may show security warnings with self-signed certs - **Private key protection**: Keep your key.pem file secure and don't commit to version control ## UTF-8 and International Content Support MailCatcher NG fully supports modern SMTP capabilities for UTF-8 and international content. ### SMTP Capabilities MailCatcher NG advertises support for: - **SMTPUTF8 (RFC 6531)**: Allows clients to send UTF-8 directly without encoding - **8BITMIME (RFC 6152)**: Accepts 8bit transfer encoding for UTF-8 content without base64 overhead - **Multiple encodings**: 7bit, 8bit, base64, and quoted-printable transfer encodings - **Charset preservation**: Automatically preserves and displays charset information ### Benefits Modern mail libraries can send UTF-8 encoded messages directly to MailCatcher NG without additional encoding overhead. This reduces message size and improves compatibility with international content. ### Supported Encodings - **7bit**: ASCII-only content - **8bit**: UTF-8 and other 8-bit encodings (RFC 6152) - **base64**: Binary-safe encoding (traditional fallback) - **quoted-printable**: Text-optimized encoding ### Character Display MailCatcher NG properly displays: - International characters and scripts - Multiple languages in a single message - Proper charset detection and preservation - Emoji and Unicode content ### Testing UTF-8 Content Use the provided example scripts to test UTF-8 handling: ```bash SMTP_HOST=127.0.0.1 SMTP_PORT=1025 ruby send_example_emails.rb ``` This sends messages with various UTF-8 encodings for testing and verification. ## Advanced Email Features ### Email Authentication Verification MailCatcher NG verifies and displays: - **DMARC (Domain-based Message Authentication, Reporting and Conformance)**: Domain policy enforcement - **DKIM (DomainKeys Identified Mail)**: Message signature verification - **SPF (Sender Policy Framework)**: Authorized sender verification These authentication results are displayed in the web interface. ### Email Encryption and Signatures MailCatcher NG can display: - **S/MIME (Secure/Multipurpose Internet Mail Extensions)**: Certificate-based encryption and signatures - **OpenPGP**: PGP-based encryption and signatures Both encrypted and signed messages are properly handled and displayed. ### BIMI Support **Brand Indicators for Message Identification (BIMI)** display authenticated brand logos in email clients. MailCatcher NG supports viewing BIMI data associated with authenticated messages. ### Advanced Preview Text Extraction MailCatcher NG uses intelligent preview text extraction with a 3-tier fallback system: 1. Explicit preview header (from message metadata) 2. First plain text content (if available) 3. Plain text extraction from HTML (as last resort) ### Enhanced Sender/Recipient Parsing Improved parsing and display of: - Sender names and email addresses - Recipient lists (To, Cc, Bcc) - Reply-To addresses - Proper name encoding and display ## Server Logs and SMTP Monitoring Monitor real-time SMTP protocol interactions between your application and MailCatcher NG. The Server Logs view displays all SMTP commands, responses, and connection events. ### Accessing Server Logs 1. Visit the web interface at `http://127.0.0.1:1080` 2. Click "Server Information" in the sidebar 3. View the "Server Logs" panel on the right ![Server Logs View](https://github.com/spaquet/mailcatcher/blob/main/screenshots/logs.webp) ### Log Details Logs show: - **Timestamp**: Millisecond-precision event time - **Session ID**: Unique identifier for each SMTP connection - **Event Type**: COMMAND, RESPONSE, DATA, or CONNECTION - **Direction**: Client (→) or server (←) direction - **Message**: SMTP command, response code, or event details ### Example Log Events ```text COMMAND + client RCPT TO: RESPONSE - server 250 OK DATA + client Message complete (1145 bytes) RESPONSE - server 354 Start mail input; end with . CONNECTION - server Connection established from 127.0.0.1:55044 RESPONSE - server 250 8BITMIME SMTPUTF8 ``` ### Auto-refresh Enable **Auto-refresh: ON** toggle to continuously monitor live connections. Disable to pause and review historical logs. ### Filter Logs Use the "Filter logs..." search box to find specific: - Connection IDs - Command names (RCPT, MAIL, DATA) - Email addresses - Response codes (250, 354, 550) - Custom text patterns ### Debugging SMTP Issues Server logs are essential for troubleshooting: - **Connection refused**: Check if MailCatcher is running on `127.0.0.1:1025` - **AUTH failures**: Verify authentication commands in logs (MailCatcher doesn't require AUTH) - **Message rejections**: See exact SMTP response codes - **Protocol errors**: Identify non-standard client behavior - **UTF-8 issues**: Monitor SMTPUTF8 capability negotiation ## Message Management ### Limit Message Storage Prevent memory usage from growing unbounded: ```bash mailcatcher --messages-limit 1000 ``` Only the 1000 most recent messages are kept. Older messages are automatically deleted. ### Disable Quit Function Prevent accidental server shutdown: ```bash mailcatcher --no-quit ``` Disables the quit button in the web interface and the quit API endpoint. ## HTTP Path Prefix For reverse proxy or nested deployment scenarios: ```bash mailcatcher --http-path /mail ``` Access the web interface at `http://127.0.0.1:1080/mail/` All HTTP resources are served with the specified prefix. ## Keyboard Navigation The web interface supports keyboard shortcuts for efficient message navigation: - Arrow keys to move between messages - Shortcuts for common actions - See the web interface for full keyboard reference ## Caveats Mail processing is fairly basic but easily modified. If something doesn't work for you: 1. Fork the project 2. Fix it or add the feature 3. File an [issue](https://github.com/spaquet/mailcatcher/issues) with the complete message 4. Submit a pull request Include the whole message you're having problems with for diagnosis. --- # REST API MailCatcher NG provides a RESTful API for accessing and downloading messages programmatically. ## Endpoints ### List All Messages ``` GET /messages ``` Returns JSON array of all messages with basic metadata. **Example:** ```bash curl http://127.0.0.1:1080/messages ``` **Response:** ```json [ { "id": 1, "from": ["sender@example.com"], "to": ["recipient@example.com"], "subject": "Test Email", "created_at": "2024-01-10T10:30:00Z" }, { "id": 2, "from": ["another@example.com"], "to": ["user@example.com"], "subject": "Another Test", "created_at": "2024-01-10T10:35:00Z" } ] ``` ### Get Message Metadata ``` GET /messages/:id.json ``` Returns detailed metadata for a specific message. **Example:** ```bash curl http://127.0.0.1:1080/messages/1.json ``` ### Get HTML Version ``` GET /messages/:id.html ``` Returns the HTML version of the message. **Example:** ```bash curl http://127.0.0.1:1080/messages/1.html ``` ### Get Plain Text Version ``` GET /messages/:id.plain ``` Returns the plain text version of the message. **Example:** ```bash curl http://127.0.0.1:1080/messages/1.plain ``` ### Get Message Source ``` GET /messages/:id.source ``` Returns the complete raw email source (MIME format). **Example:** ```bash curl http://127.0.0.1:1080/messages/1.source ``` ### Download Message as EML ``` GET /messages/:id.eml ``` Downloads the complete message in EML (RFC 822) format, suitable for importing into email clients. **Example:** ```bash curl -O http://127.0.0.1:1080/messages/1.eml ``` ### Download Message Part/Attachment ``` GET /messages/:id/parts/:cid ``` Downloads a specific message part or attachment by its Content-ID (CID). **Example:** ```bash curl -O http://127.0.0.1:1080/messages/1/parts/image-001 ``` ### Get SMTP Transcript (JSON) ``` GET /messages/:id/transcript.json ``` Returns the SMTP transcript for the message as JSON, including all SMTP commands, responses, and TLS details. **Example:** ```bash curl http://127.0.0.1:1080/messages/1/transcript.json ``` **Response:** ```json { "id": 1, "session_id": "abc123def456", "client_ip": "192.168.1.100", "client_port": 54321, "server_ip": "127.0.0.1", "server_port": 1025, "tls_enabled": true, "tls_protocol": "TLSv1.2", "tls_cipher": "ECDHE-RSA-AES256-GCM-SHA384", "connection_started_at": "2024-01-10T10:30:00Z", "connection_ended_at": "2024-01-10T10:30:05Z", "entries": [ { "type": "client", "command": "EHLO client.example.com", "timestamp": "2024-01-10T10:30:00Z" }, { "type": "server", "response": "250-localhost Hello client.example.com", "timestamp": "2024-01-10T10:30:00Z" } ], "created_at": "2024-01-10T10:30:05Z" } ``` ### Get SMTP Transcript (HTML) ``` GET /messages/:id.transcript ``` Returns the SMTP transcript for the message rendered as an HTML page, useful for viewing in a browser. **Example:** ```bash curl http://127.0.0.1:1080/messages/1.transcript ``` ### Delete Message ``` DELETE /messages/:id ``` Deletes a specific message from storage. **Example:** ```bash curl -X DELETE http://127.0.0.1:1080/messages/1 ``` ### Delete All Messages ``` DELETE /messages ``` Clears all stored messages. **Example:** ```bash curl -X DELETE http://127.0.0.1:1080/messages ``` ## System Endpoints ### WebSocket Connection for Real-Time Updates ``` GET /messages (with WebSocket upgrade) ``` Upgrades the HTTP connection to WebSocket for receiving real-time notifications about new messages, deletions, and clears. **Example:** ```javascript const ws = new WebSocket('ws://127.0.0.1:1080/messages'); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'add') { console.log('New message received:', data.message); } else if (data.type === 'remove') { console.log('Message deleted:', data.id); } else if (data.type === 'clear') { console.log('All messages cleared'); } }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ``` **Message Types:** - `add` - New message arrived (includes full message object) - `remove` - Message was deleted (includes message id) - `clear` - All messages were cleared ### Server Information ``` GET /server-info ``` Returns server configuration and status information. **Example:** ```bash curl http://127.0.0.1:1080/server-info ``` **Response includes:** - MailCatcher version - HTTP server port - SMTP server port - Hostname and IP addresses - Connection counts - Other configuration details ### WebSocket Test Interface ``` GET /websocket-test ``` Serves a web page for testing WebSocket connectivity and real-time message updates. **Example:** ```bash curl http://127.0.0.1:1080/websocket-test ``` ### Quit/Shutdown Server ``` DELETE / ``` Terminates the MailCatcher server instance. **Example:** ```bash curl -X DELETE http://127.0.0.1:1080/ ``` **Response:** - `204 No Content` - Server is shutting down - `403 Forbidden` - Server is not configured to allow remote shutdown ## Advanced Endpoints ### Search / Filter Messages ``` GET /messages/search?q=query&has_attachments=true&from=2024-01-01&to=2024-01-31 ``` Searches messages across subject, sender, recipient, and body content with optional filtering. **Parameters:** - `q` - Search query string (searches subject, sender, recipients, and body) - `has_attachments` - Filter by attachment presence (`true` or `false`) - `from` - Start date for filtering (ISO 8601 format, e.g., `2024-01-01`) - `to` - End date for filtering (ISO 8601 format, e.g., `2024-12-31`) **Example:** ```bash curl "http://127.0.0.1:1080/messages/search?q=verification&has_attachments=false" ``` **Response:** ```json [ { "id": 1, "sender": "noreply@example.com", "recipients": ["user@example.com"], "subject": "Email Verification Required", "size": "1234", "created_at": "2024-01-10T10:30:00Z" } ] ``` ### Extract Verification Tokens / Codes / Links ``` GET /messages/:id/extract?type=token|link|otp ``` Extracts verification tokens, magic links, OTP codes, or reset tokens from message content. **Parameters:** - `type` - Type of token to extract: `link` (magic links), `otp` (6-digit codes), or `token` (reset tokens) **Example:** ```bash curl "http://127.0.0.1:1080/messages/1/extract?type=otp" ``` **Response:** ```json [ { "type": "otp", "value": "123456", "context": "Your verification code is: 123456. This code will expire in 10 minutes." } ] ``` ### Extract All Links with Context ``` GET /messages/:id/links.json ``` Returns all links found in the message with metadata about their purpose. **Example:** ```bash curl http://127.0.0.1:1080/messages/1/links.json ``` **Response:** ```json [ { "href": "https://example.com/verify?token=abc123xyz", "text": "Verify Your Email", "is_verification": true, "is_unsubscribe": false }, { "href": "https://example.com/unsubscribe", "text": "Unsubscribe", "is_verification": false, "is_unsubscribe": true } ] ``` ### Parse & Return Structured Data ``` GET /messages/:id/parsed.json ``` Returns comprehensive structured data parsed from the message, including verification URLs, OTP codes, reset tokens, unsubscribe links, and all message links. **Example:** ```bash curl http://127.0.0.1:1080/messages/1/parsed.json ``` **Response:** ```json { "verification_url": "https://example.com/verify?token=abc123", "otp_code": "123456", "reset_token": "https://example.com/reset?token=xyz789", "unsubscribe_link": "https://example.com/unsubscribe", "all_links": [ { "href": "https://example.com/verify?token=abc123", "text": "Verify Your Email", "is_verification": true, "is_unsubscribe": false } ] } ``` ### Check Render / Accessibility Score ``` GET /messages/:id/accessibility.json ``` Analyzes the HTML email for accessibility issues and returns a score (0-100) with recommendations. **Example:** ```bash curl http://127.0.0.1:1080/messages/1/accessibility.json ``` **Response:** ```json { "score": 85, "breakdown": { "images_with_alt": 100, "semantic_html": 50 }, "recommendations": [ "Use semantic HTML tags (header, main, article, section)" ] } ``` **Score Breakdown:** - `images_with_alt` - Percentage of images with alt text (0-100) - `semantic_html` - Whether semantic HTML tags are used (50 = no, 100 = yes) - `score` - Overall accessibility score (average of all metrics) ### Forward Message (SMTP) ``` POST /messages/:id/forward ``` Forwards the caught email message to its original recipient(s) using a configured SMTP server. Useful for final validation after testing. **Configuration Required:** Start MailCatcher with SMTP forwarding configuration: ```bash mailcatcher \ --forward-smtp-host smtp.example.com \ --forward-smtp-port 587 \ --forward-smtp-user your-username@example.com \ --forward-smtp-password your-password ``` **Example:** ```bash curl -X POST http://127.0.0.1:1080/messages/1/forward ``` **Response (Success):** ```json { "success": true, "forwarded_to": ["user@example.com"], "forwarded_at": "2024-01-10T10:30:00Z" } ``` **Response (Error - SMTP not configured):** ```json { "error": "SMTP not configured" } ``` ## Usage Examples ### Check for New Messages ```bash #!/bin/bash MAILCATCHER_URL="http://127.0.0.1:1080" # Get all messages messages=$(curl -s $MAILCATCHER_URL/messages) # Check message count count=$(echo $messages | jq '. | length') echo "Total messages: $count" # Extract first message details echo $messages | jq '.[0]' ``` ### Extract Email Content ```bash # Get HTML content curl -s http://127.0.0.1:1080/messages/1.html > email.html # Get plain text curl -s http://127.0.0.1:1080/messages/1.plain > email.txt # Get raw source curl -s http://127.0.0.1:1080/messages/1.source > email.eml ``` ### Download Attachments ```bash # List message parts (in JSON metadata) curl -s http://127.0.0.1:1080/messages/1.json | jq '.parts' # Download specific attachment by CID curl -O http://127.0.0.1:1080/messages/1/parts/attachment-id ``` ### Inspect SMTP Transcript ```bash # Get SMTP transcript as JSON curl -s http://127.0.0.1:1080/messages/1/transcript.json | jq '.' # Extract TLS information curl -s http://127.0.0.1:1080/messages/1/transcript.json | jq '.tls_protocol, .tls_cipher' # View in browser open http://127.0.0.1:1080/messages/1.transcript ``` ### Automated Testing Use the API in your test suite to verify email delivery: ```bash #!/bin/bash # Wait for message max_attempts=10 attempt=0 while [ $attempt -lt $max_attempts ]; do messages=$(curl -s http://127.0.0.1:1080/messages) count=$(echo $messages | jq '. | length') if [ $count -gt 0 ]; then echo "Email received!" exit 0 fi sleep 1 ((attempt++)) done echo "Email not received" exit 1 ``` ## Real-Time Message Monitoring Monitor incoming messages in real-time using WebSocket: ```bash #!/bin/bash # Simple WebSocket client using websocat (install with: brew install websocat) websocat ws://127.0.0.1:1080/messages | while read line; do echo "Update: $line" | jq '.' done ``` Or using Python: ```python import websocket import json def on_message(ws, message): data = json.loads(message) print(f"Received: {data['type']}") if data['type'] == 'add': print(f"New message: {data['message']['subject']}") def on_error(ws, error): print(f"Error: {error}") def on_close(ws, close_status_code, close_msg): print("Connection closed") ws = websocket.WebSocketApp("ws://127.0.0.1:1080/messages", on_message=on_message, on_error=on_error, on_close=on_close) ws.run_forever() ``` ## Notes - All timestamps are in ISO 8601 format - Message IDs are sequential integers - Content-IDs for attachments are extracted from message headers - API responses use standard HTTP status codes - No authentication is required (suitable for local development only) - WebSocket connections persist until closed by client or server - Real-time updates are broadcast to all connected WebSocket clients ## Complete API Reference | Method | Endpoint | Description | | ------ | -------- | ----------- | | GET | `/` | Web UI | | GET | `/server-info` | Server info and configuration | | GET | `/websocket-test` | WebSocket test interface | | DELETE | `/` | Shutdown server | | GET | `/messages` | List messages or WebSocket upgrade | | GET | `/messages/search` | Search messages by query and filters | | DELETE | `/messages` | Clear all messages | | GET | `/messages/:id.json` | Message metadata (JSON) | | GET | `/messages/:id.html` | Message body (HTML format) | | GET | `/messages/:id.plain` | Message body (plain text format) | | GET | `/messages/:id.source` | Raw MIME source | | GET | `/messages/:id.eml` | Download as EML file | | GET | `/messages/:id/transcript.json` | SMTP transcript (JSON) | | GET | `/messages/:id.transcript` | SMTP transcript (HTML) | | GET | `/messages/:id/parts/:cid` | Message part/attachment by Content-ID | | GET | `/messages/:id/extract` | Extract tokens, OTPs, or magic links | | GET | `/messages/:id/links.json` | Extract all links with context | | GET | `/messages/:id/parsed.json` | Parse structured data from message | | GET | `/messages/:id/accessibility.json` | Check accessibility score | | POST | `/messages/:id/forward` | Forward message to recipients via SMTP | | DELETE | `/messages/:id` | Delete specific message | --- # Framework & Application Integration Configure your favorite framework or application to send mail through MailCatcher. ## Rails Add this to your `config/environments/development.rb`: ```ruby config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1025 } config.action_mailer.raise_delivery_errors = false ``` With STARTTLS enabled: ```ruby config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1025, enable_starttls_auto: true } ``` With direct TLS (SMTPS): ```ruby config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1465, enable_starttls_auto: false, ssl: true } ``` ## Django Add the following configuration to your `settings.py`: ```python if DEBUG: EMAIL_HOST = '127.0.0.1' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 1025 EMAIL_USE_TLS = False ``` With direct TLS (SMTPS): ```python if DEBUG: EMAIL_HOST = '127.0.0.1' EMAIL_PORT = 1465 # Direct TLS EMAIL_USE_TLS = True EMAIL_USE_SSL = True ``` ## PHP Use the `catchmail` command to send mail via MailCatcher. Set [PHP's mail configuration](https://www.php.net/manual/en/mail.configuration.php) in your [php.ini](https://www.php.net/manual/en/configuration.file.php): ```ini sendmail_path = /usr/bin/env catchmail -f some@from.address ``` Or in your [Apache configuration](https://www.php.net/manual/en/configuration.changes.php): ``` php_admin_value sendmail_path "/usr/bin/env catchmail -f some@from.address" ``` ### Custom SMTP Server If you've started MailCatcher on alternative SMTP IP and/or port with parameters like `--smtp-ip 192.168.0.1 --smtp-port 10025`, add the same parameters to your `catchmail` command: ```ini sendmail_path = /usr/bin/env catchmail --smtp-ip 192.168.0.1 --smtp-port 10025 -f some@from.address ``` ### RVM Compatibility If installed via RVM, `catchmail` may not be available in your system PATH. Run `which catchmail` to get the full path: ```ini sendmail_path = /path/to/rvm/rubies/ruby-X.X.X/bin/catchmail -f some@from.address ``` ### Popular Platforms - **Drupal**: Set the mail system to use `catchmail` via appropriate modules - **WordPress**: Use a mail plugin configured to use the local sendmail path - **Other PHP applications**: Refer to the application's mail configuration documentation ## Docker The official MailCatcher Docker image is available on [Docker Hub](https://hub.docker.com/r/stpaquet/alpinemailcatcher): ### Basic Setup ```bash docker run -d -p 1080:1080 -p 1025:1025 stpaquet/alpinemailcatcher ``` ### Docker Compose ```yaml version: '3.8' services: mailcatcher: image: stpaquet/alpinemailcatcher:latest ports: - "1080:1080" - "1025:1025" environment: MAILCATCHER_ENV: development app: image: your-app:latest depends_on: - mailcatcher environment: SMTP_HOST: mailcatcher SMTP_PORT: 1025 ``` ### Configuration Configure your application container to connect to the mailcatcher service: - **Host**: `mailcatcher` (when using Docker Compose) - **SMTP Port**: `1025` - **HTTP Port**: `1080` ### Image Details - Alpine Linux based for minimal size and quick startup - Pre-configured with all dependencies - Ready to use with any mail-sending application --- # MCP Server Setup for MailCatcher NG MailCatcher NG includes a built-in MCP (Model Context Protocol) server that allows Claude and other MCP-compatible clients to interact with caught emails programmatically. ## Quick Start ### Option 1: Command Line Start MailCatcher with MCP enabled: ```bash mailcatcher --mcp --foreground ``` This will: 1. Start the normal MailCatcher SMTP and HTTP servers 2. Start the MCP server over stdio 3. Output available tools to stderr ### Option 2: Docker When using Docker, add the `--mcp` flag: ```bash docker run -p 1025:1025 -p 1080:1080 mailcatcher/mailcatcher-ng --mcp --foreground ``` ## Using with Claude Desktop Claude Desktop's built-in configuration allows you to add custom MCP servers. ### 1. Create Configuration Create or edit `~/.claude_desktop_config.json`: ```json { "mcpServers": { "mailcatcher": { "command": "mailcatcher", "args": ["--mcp", "--foreground"] } } } ``` ### 2. Configure MailCatcher Options (Optional) If you need to customize MailCatcher settings: ```json { "mcpServers": { "mailcatcher": { "command": "mailcatcher", "args": [ "--mcp", "--foreground", "--smtp-port", "1025", "--http-port", "1080", "--persistence" ] } } } ``` ### 3. Restart Claude After updating the config, restart Claude Desktop. ## Available Tools The MCP server exposes 7 tools: ### 1. `search_messages` Search through caught emails with flexible filtering. **Parameters:** - `query` (string, required): Search term (searches subject, sender, recipients, body) - `limit` (integer, optional, default: 5): Maximum results - `has_attachments` (boolean, optional): Filter to only messages with attachments - `from_date` (string, optional): ISO 8601 datetime to search from - `to_date` (string, optional): ISO 8601 datetime to search until **Example:** ``` Search for emails from noreply@example.com ``` ### 2. `get_latest_message_for` Get the latest email received by a specific recipient. **Parameters:** - `recipient` (string, required): Email address to match in recipients - `subject_contains` (string, optional): Only return if subject contains this text **Example:** ``` Get the latest email to user@example.com about password reset ``` ### 3. `extract_token_or_link` Extract authentication tokens or links from a message. **Parameters:** - `message_id` (integer, required): Message ID - `kind` (string, required): `magic_link`, `otp`, `reset_token`, or `all` **Example:** ``` Extract the OTP code from message 5 ``` ### 4. `get_parsed_auth_info` Get structured authentication information from a message. **Parameters:** - `message_id` (integer, required): Message ID **Returns:** - `verification_url`: First magic link found - `otp_code`: First OTP code found - `reset_token`: First reset token found - `unsubscribe_link`: Unsubscribe link from List-Unsubscribe header - `links_count`: Total number of links ### 5. `get_message_preview_html` Get HTML preview of a message (responsive for mobile if requested). **Parameters:** - `message_id` (integer, required): Message ID - `mobile` (boolean, optional, default: false): Return mobile-optimized preview **Returns:** - Full HTML content (truncated at 200KB if very large) - Character set information ### 6. `delete_message` Delete a specific message by ID. **Parameters:** - `message_id` (integer, required): Message ID to delete ### 7. `clear_messages` Delete all caught messages (destructive operation). **Parameters:** None ## Common Use Cases ### Testing Email-Based Authentication ``` Claude: "I'm testing a login flow. Send a test email to test@example.com and extract the verification link." [Claude creates a test email] Claude: "Now find the latest email to test@example.com and get the verification URL." Claude uses: get_latest_message_for(recipient: "test@example.com", subject_contains: "verify") Claude uses: get_parsed_auth_info(message_id: 1) ``` ### Debugging Email Content ``` Claude: "Show me the HTML preview of message 3, optimized for mobile" Claude uses: get_message_preview_html(message_id: 3, mobile: true) ``` ### Searching Email History ``` Claude: "Find all emails from send@newsletter.com that arrived in the last hour" Claude uses: search_messages(query: "send@newsletter.com", from_date: "2024-01-12T15:00:00Z", to_date: "2024-01-12T16:00:00Z") ``` ## Troubleshooting ### MCP Server Not Starting 1. Check that MailCatcher is running: ```bash mailcatcher --mcp --foreground -v ``` 2. Verify no port conflicts: ```bash lsof -i :1025 # Check SMTP port lsof -i :1080 # Check HTTP port ``` 3. Check stderr for errors: - MCP logging is sent to stderr, not stdout - Look for `[MCP Server]` log lines ### Tools Not Available 1. Check Claude can see the tools: - In Claude, type `@mailcatcher` to see available tools - Tools should appear in the tool selector 2. Verify MCP server is running: ```bash ps aux | grep mailcatcher ``` ### Message Not Found 1. Ensure the message ID is correct 2. Check the HTTP UI to see available messages: http://localhost:1080/ ## Performance Notes - Message searches are limited to configurable max results (default: 50) - Large HTML previews are truncated at 200KB for performance - First 10 links are returned from `get_parsed_auth_info` to keep responses manageable - Search queries should be specific to avoid long response times ## Security Considerations - The MCP server runs over stdio (in-process) - no network exposure - No authentication is required (assumes localhost-only MailCatcher) - Messages contain email content - keep MCP server access restricted to trusted users - For remote access, use additional network-level security controls ## Advanced Configuration ### Environment Variables ```bash # Enable verbose logging export MAILCATCHER_ENV=development mailcatcher --mcp --foreground # Use specific database export MAILCATCHER_HOME=~/.my_mailcatcher mailcatcher --mcp --persistence ``` ### Programmatic Access You can also call MCP tools directly from Ruby: ```ruby require 'mail_catcher/integrations/mcp_tools' # Search for messages results = MailCatcher::Integrations::MCPTools.call_tool(:search_messages, { query: "from:test@example.com", limit: 10 }) # Extract tokens tokens = MailCatcher::Integrations::MCPTools.call_tool(:extract_token_or_link, { message_id: 1, kind: "otp" }) ``` ## Next Steps - See [CLAUDE_PLUGIN_SETUP.md](https://github.com/spaquet/mailcatcher/blob/main/reference/CLAUDE_PLUGIN_SETUP.md) for using the Claude Plugin (no installation needed) - See [INTEGRATION_ARCHITECTURE.md](https://github.com/spaquet/mailcatcher/blob/main/reference/INTEGRATION_ARCHITECTURE.md) for detailed architecture information --- # Claude Plugin Setup for MailCatcher NG MailCatcher NG can be used as a Claude Plugin, giving Claude direct access to all mail inspection features without requiring any special installation on your machine. ## Quick Start ### 1. Start MailCatcher with Plugin Support ```bash mailcatcher --plugin --foreground ``` Or enable both MCP and Plugin: ```bash mailcatcher --mcp --plugin --foreground ``` ### 2. Add Plugin to Claude In Claude.com or Claude Desktop: 1. Open settings/plugins menu 2. Select "Create a plugin" 3. Paste this plugin manifest URL (or install manually below): ``` http://localhost:1080/.well-known/ai-plugin.json ``` 4. Click "Install" or "Add" That's it! Claude now has access to all MailCatcher tools. ## Manual Plugin Installation If the automatic discovery doesn't work: 1. Go to https://claude.com (or open Claude Desktop) 2. Open the plugin settings 3. Click "Create a plugin" 4. Provide these details: - **Name:** MailCatcher NG - **Plugin URL:** `http://localhost:1080/.well-known/ai-plugin.json` - **API Base URL:** `http://localhost:1080` ## Using the Plugin with Claude Once installed, you can interact with MailCatcher through natural language: ### Examples **Search for emails:** ``` Claude: "Search my emails for messages from noreply@example.com" ``` **Extract authentication codes:** ``` Claude: "What's the OTP code in the latest email to admin@test.com?" ``` **Get email previews:** ``` Claude: "Show me the HTML preview of message 1 optimized for mobile" ``` **Manage messages:** ``` Claude: "Clear all my test emails" ``` ## Available Plugin Endpoints The plugin exposes HTTP endpoints that Claude uses: ### POST /plugin/search Search through emails. **Parameters:** - `query` (string, required): Search term - `limit` (integer, optional): Max results (default: 5) **Example:** ```json POST /plugin/search?query=password&limit=10 ``` ### GET /plugin/message/{id}/latest Get latest message for a recipient. **Parameters:** - `recipient` (string, required): Email address - `subject_contains` (string, optional): Subject filter **Example:** ``` GET /plugin/message/1/latest?recipient=user@example.com&subject_contains=verify ``` ### GET /plugin/message/{id}/tokens Extract tokens from a message. **Parameters:** - `id` (integer, path): Message ID - `kind` (string, optional): `magic_link`, `otp`, `reset_token`, or `all` **Example:** ``` GET /plugin/message/1/tokens?kind=otp ``` ### GET /plugin/message/{id}/auth-info Get structured authentication information. **Parameters:** - `id` (integer, path): Message ID **Returns:** ```json { "verification_url": "https://example.com/verify?token=...", "otp_code": "123456", "reset_token": "...", "unsubscribe_link": "...", "links_count": 5 } ``` ### GET /plugin/message/{id}/preview Get HTML preview of a message. **Parameters:** - `id` (integer, path): Message ID - `mobile` (boolean, optional): Mobile-optimized (default: false) **Returns:** HTML content ### DELETE /plugin/messages Delete all messages. **Returns:** 204 No Content ### DELETE /plugin/message/{id} Delete a specific message. **Parameters:** - `id` (integer, path): Message ID **Returns:** 204 No Content ## Plugin vs MCP: Which Should I Use? ### Use the Plugin if: - You want to interact with Claude.com or Claude Desktop - You don't want to configure anything beyond starting MailCatcher - You prefer natural language interactions - You're testing email workflows with Claude ### Use MCP if: - You need programmatic access from other tools - You want to integrate with Claude Desktop configurations - You need more precise tool control - You're building automated test workflows ### Use Both if: - You want maximum flexibility - You need both natural language (plugin) and programmatic (MCP) access - You're running a shared testing environment ```bash mailcatcher --mcp --plugin --foreground ``` ## Configuration ### Remote Access If MailCatcher is on a different machine: 1. Start MailCatcher with the `--http-ip` flag: ```bash mailcatcher --plugin --http-ip 0.0.0.0 --foreground ``` 2. Update the plugin URL in Claude: - Change `localhost` to your server's IP or hostname - Example: `http://192.168.1.100:1080/.well-known/ai-plugin.json` ### HTTPS (Optional, for remote deployments) For production deployments, use HTTPS: 1. Set up a reverse proxy (nginx, caddy, etc.) 2. Configure the plugin URL to use `https://` 3. Ensure SSL certificates are valid ## Troubleshooting ### Plugin Not Appearing in Claude 1. **Check MailCatcher is running:** ```bash curl http://localhost:1080/.well-known/ai-plugin.json ``` 2. **Clear Claude's cache:** - Reload the page - Log out and log back in 3. **Verify plugin endpoint is accessible:** ```bash curl http://localhost:1080/plugin/openapi.json ``` ### "Unable to reach plugin" Error 1. **Check MailCatcher is running:** ```bash ps aux | grep mailcatcher ``` 2. **Verify port is correct:** ```bash lsof -i :1080 ``` 3. **Test connectivity:** ```bash curl -v http://localhost:1080/version.json ``` ### Plugin Commands Not Working 1. **Check for errors in HTTP response:** ```bash curl -X POST "http://localhost:1080/plugin/search?query=test" -v ``` 2. **Verify message exists:** - Go to http://localhost:1080 in your browser - Check if messages are actually present 3. **Check MailCatcher logs:** ```bash mailcatcher --plugin --foreground -v ``` ## Using with Automated Testing The plugin can be used in test workflows: ```python # Python example using Claude SDK from anthropic import Anthropic client = Anthropic() # Start MailCatcher with plugin first! # mailcatcher --plugin --foreground response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, messages=[ { "role": "user", "content": "Search for emails from support@example.com and tell me the subject lines" } ] ) print(response.content[0].text) ``` ## Performance Considerations - Search results are limited to configurable max (default: 5) - Large HTML previews are truncated at 200KB - Limit returned from `auth-info` endpoint is 10 links For better performance with large datasets: - Use specific search queries - Limit result sizes - Regular cleanup of old messages ## Security Notes - The plugin communicates over HTTP (uses localhost) - No authentication is required - Messages contain email content - keep access restricted - For production use, implement network security controls ## Next Steps - See [MCP_SETUP.md](https://github.com/spaquet/mailcatcher/blob/main/reference/MCP_SETUP.md) for programmatic access via MCP - See [INTEGRATION_ARCHITECTURE.md](https://github.com/spaquet/mailcatcher/blob/main/reference/INTEGRATION_ARCHITECTURE.md) for technical details - Check README.md for general MailCatcher documentation