### Starting Mailpit Server Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Example of how to start the Mailpit server programmatically. Ensure configuration is verified and the database is initialized before starting the server. ```go package main import ( "github.com/axllent/mailpit/config" "github.com/axllent/mailpit/internal/storage" "github.com/axllent/mailpit/server" ) func main() { // Load configuration if err := config.VerifyConfig(); err != nil { log.Fatal(err) } // Initialize database if err := storage.InitDB(); err != nil { log.Fatal(err) } defer storage.Close() // Start HTTP server (blocks) server.Listen() } ``` -------------------------------- ### Start Mailpit with Defaults Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit using its default settings. Access the UI at http://localhost:8025 and SMTP at localhost:1025. ```bash mailpit ``` -------------------------------- ### Start SMTP Server Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Initiates the Mailpit SMTP server listener. ```go Listen() ``` -------------------------------- ### Start HTTP Server Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Starts the Mailpit HTTP server. This function initializes the WebSocket hub, registers API routes, starts the POP3 server if configured, binds to the configured HTTP address, applies TLS if configured, and blocks until the server exits or an error occurs. It uses configuration settings for the bind address, TLS certificates, API base path, and UI authentication. ```Go import "github.com/axllent/mailpit/server" // Start HTTP server (blocks) go server.Listen() // Server runs in background, handle graceful shutdown ``` -------------------------------- ### Install Mailpit via Script (Linux & Mac) Source: https://github.com/axllent/mailpit/blob/develop/README.md Installs Mailpit to /usr/local/bin/mailpit. Ensure you have curl and sh installed. ```shell sudo sh < <(curl -sL https://raw.githubusercontent.com/axllent/mailpit/develop/install.sh) ``` -------------------------------- ### Basic Mailpit Configuration Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit with basic SMTP and HTTP listening ports. ```bash mailpit --smtp 0.0.0.0:1025 --listen 0.0.0.0:8025 ``` -------------------------------- ### SMTP Auto-Relay Usage Examples Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Demonstrates starting the Mailpit SMTP server with auto-relay enabled, either via a configuration file or environment variables. Supports relaying all messages or only those matching specific recipient patterns. ```bash # Relay all messages mailpit --smtp-relay-config relay.yaml --smtp-relay-all # Relay only to specific recipients mailpit --smtp-relay-config relay.yaml --smtp-relay-matching ".*@production.com" # Via environment variables MP_SMTP_RELAY_HOST=smtp.gmail.com \ MP_SMTP_RELAY_PORT=587 \ MP_SMTP_RELAY_STARTTLS=true \ MP_SMTP_RELAY_AUTH=plain \ MP_SMTP_RELAY_USERNAME=sender@gmail.com \ MP_SMTP_RELAY_PASSWORD=app-password \ MP_SMTP_RELAY_ALL=true \ mailpit ``` -------------------------------- ### Start Mailpit with Authentication Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Runs Mailpit with UI authentication enabled. A password file must be created first using `htpasswd`. ```bash # Create password file htpasswd -c ui.auth myuser # Run with auth mailpit --ui-auth-file ui.auth ``` -------------------------------- ### Install Mailpit with Custom Path via Script (Linux & Mac) Source: https://github.com/axllent/mailpit/blob/develop/README.md Installs Mailpit to a custom path specified by the INSTALL_PATH environment variable. Ensure you have curl and sh installed. ```shell sudo INSTALL_PATH=/usr/bin sh < <(curl -sL https://raw.githubusercontent.com/axllent/mailpit/develop/install.sh) ``` -------------------------------- ### POP3 Authentication Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Demonstrates the POP3 authentication sequence using USER and PASS commands. This is a common method for authenticating POP3 clients. ```text USER username +OK PASS password +OK ``` -------------------------------- ### Mailpit Configuration with Authentication Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit with UI and SMTP authentication enabled using specified auth files. ```bash mailpit --ui-auth-file ui.auth --smtp-auth-file smtp.auth ``` -------------------------------- ### server.Listen Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Starts the HTTP server, initializing WebSocket hubs, registering API routes, and binding to the configured address. This function blocks until the server exits or an error occurs. ```APIDOC ## Listen Starts the HTTP server. ### Signature ```go func Listen() ``` ### Behavior - Initializes WebSocket hub for real-time updates - Registers all API routes - Starts POP3 server if configured - Binds to configured HTTP address - Applies TLS if configured - Blocks until server exits or error ### Configuration Used - `config.HTTPListen` - Bind address:port - `config.UITLSCert/Key` - TLS certificates - `config.Webroot` - API base path - `auth.UICredentials` - Web UI authentication ### Example ```go import "github.com/axllent/mailpit/server" // Start HTTP server (blocks) go server.Listen() // Server runs in background, handle graceful shutdown ``` ``` -------------------------------- ### Accessing Mailpit Version Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/config.md Example of how to access and print the Mailpit version using the `Version` variable. ```go fmt.Printf("Mailpit version: %s\n", config.Version) ``` -------------------------------- ### Server Configuration via Environment Variables Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Provides examples of common environment variables used to configure Mailpit server settings, including bind addresses, authentication, and CORS. ```bash # Bind addresses MP_UI_BIND_ADDR=0.0.0.0:8025 MP_SMTP_BIND_ADDR=0.0.0.0:1025 MP_POP3_BIND_ADDR=0.0.0.0:1110 # Web root MP_WEBROOT=/mailpit/ # Authentication MP_UI_AUTH_FILE=/etc/mailpit/ui.auth MP_UI_AUTH="username:password" # TLS MP_UI_TLS_CERT=/etc/ssl/cert.pem MP_UI_TLS_KEY=/etc/ssl/key.pem # CORS MP_API_CORS="example.com,foo.com" # Compression MP_DISABLE_HTTP_COMPRESSION=false ``` -------------------------------- ### VerifyConfig Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/config.md Validates and initializes the application's configuration. This function must be called before the application starts to ensure all settings are correct and necessary resources are prepared. ```APIDOC ## VerifyConfig ### Description Validate and initialize configuration. ### Returns - `error`: Configuration error if validation fails ### Behavior - Validates all configuration options - Compiles regular expressions - Sets up TLS certificates (including auto-generation) - Parses configuration files - Initializes security headers - Verifies file permissions ### Must be called Before starting the application ### Example ```go import "github.com/axllent/mailpit/config" if err := config.VerifyConfig(); err != nil { log.Fatalf("Config error: %v", err) } // Config is now ready to use ``` ### Source `config/config.go` ``` -------------------------------- ### Start SMTP Server Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Initiates the SMTP server, binding to the configured address and handling incoming connections. It validates commands, stores messages, and applies relay/forwarding rules. Requires configuration for bind address, authentication, TLS, and message limits. ```go import "github.com/axllent/mailpit/internal/smtpd" // Start SMTP server (blocks until error) if err := smtpd.Listen(); err != nil { log.Fatal(err) } ``` -------------------------------- ### SMTP Authentication Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Illustrates the SMTP authentication process using AUTH PLAIN command with base64 encoded credentials. Requires TLS for PLAIN and LOGIN methods. ```text EHLO client.example.com AUTH PLAIN dXNlcm5hbWU6cGFzc3dvcmQ= 250 2.7.0 Authentication successful ``` -------------------------------- ### Check Mailpit Version Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Displays the current installed version of Mailpit. ```bash mailpit --version ``` -------------------------------- ### Listen Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Starts the SMTP server, binding to the configured address and handling incoming mail delivery. It validates commands, stores messages, applies relay and forwarding rules, and supports STARTTLS/TLS. ```APIDOC ## Listen ### Description Starts the SMTP server. This function blocks until an error occurs. ### Function Signature ```go func Listen() error ``` ### Returns - `error`: An error if the server fails to start or encounters a critical issue during operation. ### Behavior - Binds to the configured SMTP address (specified by the `--smtp` flag). - Accepts incoming client connections. - Validates standard SMTP commands (HELO, MAIL FROM, RCPT TO, DATA). - Stores accepted messages using the configured storage mechanism (`storage.Store()`). - Applies auto-relay and forwarding rules as configured. - Enables STARTTLS or TLS encryption if configured. - Enforces message size limits defined by `config.MaxMessageSize`. ### Configuration Used - `config.SMTPListen`: The bind address and port for the SMTP server. - `config.SMTPAuthFile`: Path to the file containing authentication credentials. - `config.SMTPTLSCert/Key`: Paths to TLS certificate and key files. - `config.SMTPRequireSTARTTLS`: Boolean to enforce STARTTLS. - `config.SMTPRequireTLS`: Boolean to enforce SSL/TLS. - `config.MaxMessageSize`: Maximum allowed message size in MB. - `config.SMTPMaxRecipients`: Maximum number of recipients per message. ### Example Usage ```go import ( "log" "github.com/axllent/mailpit/internal/smtpd" ) // Start SMTP server (blocks until error) if err := smtpd.Listen(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Run Mailpit with Docker Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Launches Mailpit using a Docker container. This example maps ports for UI and SMTP and sets environment variables for bind addresses. ```bash docker run -e MP_UI_BIND_ADDR=0.0.0.0:8025 \ -e MP_SMTP_BIND_ADDR=0.0.0.0:1025 \ -p 8025:8025 \ -p 1025:1025 \ axllent/mailpit ``` -------------------------------- ### Enable Prometheus Metrics (Integration Mode) Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Starts Mailpit with Prometheus metrics enabled on the main server port. Access the metrics endpoint at `http://localhost:8025/metrics`. ```bash mailpit --enable-prometheus=true # Access metrics at: # http://localhost:8025/metrics ``` -------------------------------- ### GET /api/v1/webui Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves configuration details for the Mailpit Web UI. ```APIDOC ## GET /api/v1/webui ### Description Retrieves configuration details for the Mailpit Web UI. ### Method GET ### Endpoint /api/v1/webui ``` -------------------------------- ### Enable Prometheus Metrics (Separate Server Mode) Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Starts Mailpit with Prometheus metrics on a dedicated port. Specify the host and port for the metrics server. Access the metrics endpoint at `http://localhost:9090/metrics`. ```bash mailpit --enable-prometheus=0.0.0.0:9090 # Access metrics at: # http://localhost:9090/metrics ``` -------------------------------- ### Handle Specific Errors Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Implement this pattern to check for and handle specific errors returned by the storage package. This example shows how to return a 404 for 'message not found' and a 500 for other errors. ```go // Check for specific errors if err == "message not found" { return 404 } else if err != nil { return 500 } ``` -------------------------------- ### Verify Mailpit Configuration Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/config.md Validates and initializes the application's configuration. This function must be called before starting the application to ensure all settings are correct and necessary resources like TLS certificates are set up. ```go import "github.com/axllent/mailpit/config" if err := config.VerifyConfig(); err != nil { log.Fatalf("Config error: %v", err) } // Config is now ready to use ``` -------------------------------- ### Configure Mailpit with Environment Variables Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Shows how to configure Mailpit using environment variables, prefixed with `MP_`. This example sets bind addresses for SMTP and UI, and the maximum number of messages. ```bash export MP_SMTP_BIND_ADDR=0.0.0.0:2525 export MP_UI_BIND_ADDR=0.0.0.0:8080 export MP_MAX_MESSAGES=5000 export MP_DATABASE=/var/lib/mailpit/mail.db export MP_UI_AUTH_FILE=/etc/mailpit/ui.auth mailpit ``` -------------------------------- ### Start Mailpit with HTTPS Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Configures Mailpit to use HTTPS for the UI. Self-signed certificates for localhost are generated on the fly. Access the UI at https://localhost:8025. ```bash # Generate self-signed certificate mailpit --ui-tls-cert sans:localhost \ --ui-tls-key sans:localhost # Access at https://localhost:8025 ``` -------------------------------- ### HTTP Basic Auth Header Example with curl Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Demonstrates how to authenticate with Mailpit's UI and Send API using HTTP Basic Authentication via curl. Credentials are provided in the Authorization header. ```bash # UI authentication curl -u username:password http://localhost:8025/api/v1/messages # Send API authentication curl -u api-user:api-password -X POST http://localhost:8025/api/v1/send \ -H "Content-Type: application/json" \ -d '{...}' ``` -------------------------------- ### Authorization Header Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Include this header for endpoints requiring authentication. It uses Base64 encoding for username:password credentials. ```http Authorization: Basic base64(username:password) ``` -------------------------------- ### JavaScript WebSocket Client Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md A basic JavaScript client to connect to the Mailpit WebSocket endpoint and handle incoming 'stats' and 'new_message' events. ```javascript const ws = new WebSocket('ws://localhost:8025/api/events'); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'stats') { console.log('Updated stats:', data); } else if (data.type === 'new_message') { console.log('New message:', data.id); } }; ``` -------------------------------- ### Example API Call with CORS Origin Header Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Demonstrates making an API request from a different domain, requiring the mailpit server to be configured with the corresponding CORS origin. ```bash # From https://app.example.com curl -H "Origin: https://app.example.com" \ -H "Access-Control-Request-Method: GET" \ http://localhost:8025/api/v1/messages # Requires: mailpit --api-cors "app.example.com" ``` -------------------------------- ### HTTP Basic Auth Header Example with JavaScript fetch Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Shows how to authenticate a JavaScript fetch request to Mailpit using HTTP Basic Authentication. Credentials are base64 encoded and included in the Authorization header. ```javascript const auth = btoa('username:password'); fetch('http://localhost:8025/api/v1/messages', { headers: { 'Authorization': `Basic ${auth}` } }); ``` -------------------------------- ### Configure Mailpit Authentication via Environment Variables Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Set authentication file paths or inline credentials for Mailpit services using environment variables. The mailpit process should be started after setting these variables. ```bash # Password file paths export MP_UI_AUTH_FILE=/etc/mailpit/ui.auth export MP_SEND_API_AUTH_FILE=/etc/mailpit/send-api.auth export MP_SMTP_AUTH_FILE=/etc/mailpit/smtp.auth export MP_POP3_AUTH_FILE=/etc/mailpit/pop3.auth # Inline credentials export MP_UI_AUTH="username:password" export MP_SEND_API_AUTH="api-user:api-password" export MP_SMTP_AUTH="smtp-user:smtp-password" mailpit ``` -------------------------------- ### Mailpit Configuration with SMTP Relay Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit with SMTP relay configured via a YAML file and enables relaying for all messages. ```bash mailpit --smtp-relay-config relay.yaml --smtp-relay-all ``` -------------------------------- ### Run Mailpit with SMTP Auth File Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Example of running Mailpit with a specified SMTP authentication file. This command will fail if the file does not exist or is not readable, demonstrating the error handling for missing credentials. ```bash mailpit --smtp-auth-file /nonexistent.auth ``` -------------------------------- ### Reading Configuration in Code Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/config.md Demonstrates how to import the config package, verify configuration loading, and access various configuration parameters like listening addresses and message limits. ```go package main import ( "fmt" "github.com/axllent/mailpit/config" ) func init() { // Verify config is loaded and validated if err := config.VerifyConfig(); err != nil { panic(err) } } func main() { // Access configuration fmt.Printf("SMTP listening on: %s\n", config.SMTPListen) fmt.Printf("HTTP listening on: %s\n", config.HTTPListen) fmt.Printf("Max messages: %d\n", config.MaxMessages) fmt.Printf("Max message size: %d MB\n", config.MaxMessageSize) if config.SMTPTLSCert != "" { fmt.Println("TLS enabled for SMTP") } if config.EnableSpamAssassin != "" { fmt.Printf("SpamAssassin: %s\n", config.EnableSpamAssassin) } } ``` -------------------------------- ### API Error: 400 Invalid query parameters for GET /api/v1/messages Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error is returned when the 'start' or 'limit' parameters in a GET request to `/api/v1/messages` are not valid integers. ```json { "error": "Invalid start parameter" } ``` -------------------------------- ### Get Web UI Configuration Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Fetches the configuration details for the Mailpit web user interface. This includes version, root path, and feature enablement status. ```json { "version": "1.50.0", "webroot": "/", "label": "Development", "enable_chaos": false, "send_api_enabled": true, "spamassassin_enabled": false, "enable_browser_notifications": true } ``` -------------------------------- ### Initialize Database Connection Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/storage.md Initializes the Mailpit database connection. This function handles database file creation, schema migrations, compression setup, and format validation. It should be called before any other storage operations. ```go if err := storage.InitDB(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Message SpamAssassin Check Status Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Checks a message against SpamAssassin to determine its spam score and classification. This feature requires Mailpit to be started with the `--enable-spamassassin` flag. ```json { "score": 2.5, "is_spam": false, "report": "Spam check report text" } ``` -------------------------------- ### Setting Configuration Programmatically Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/config.md Shows how to programmatically set configuration values such as listening addresses, message limits, and database paths before calling `VerifyConfig()`. ```go import "github.com/axllent/mailpit/config" // Set values before calling VerifyConfig() config.SMTPListen = "127.0.0.1:2525" config.HTTPListen = "127.0.0.1:8025" config.MaxMessages = 1000 config.Database = "/var/lib/mailpit/mail.db" // Then verify if err := config.VerifyConfig(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Handle Storage Errors Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/storage.md Example of handling errors returned by storage operations. This snippet demonstrates checking for specific errors like 'message not found' and providing appropriate HTTP responses. ```go msg, err := storage.GetMessage(id) if err != nil { if err.Error() == "message not found" { http.NotFound(w, r) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } ``` -------------------------------- ### SMTP Auto-Forward Usage Examples Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Shows how to enable Mailpit's auto-forwarding feature using either a YAML configuration file or environment variables. This directs all incoming emails to specified recipients via a configured SMTP server. ```bash mailpit --smtp-forward-config forward.yaml # Via environment MP_SMTP_FORWARD_TO="admin@example.com" \ MP_SMTP_FORWARD_HOST=smtp.example.com \ MP_SMTP_FORWARD_PORT=587 \ MP_SMTP_FORWARD_STARTTLS=true \ MP_SMTP_FORWARD_AUTH=plain \ MP_SMTP_FORWARD_USERNAME=user@example.com \ MP_SMTP_FORWARD_PASSWORD=pass \ mailpit ``` -------------------------------- ### Enable Verbose Logging and Check Logs Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit in verbose mode, directing all logs to a specified file. The `tail -f` command is then used to monitor the log file in real-time. ```bash mailpit --verbose --log-file /tmp/mailpit.log tail -f /tmp/mailpit.log ``` -------------------------------- ### InitDB Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/storage.md Initializes the database connection, creating the database file if necessary, applying migrations, and setting up compression. ```APIDOC ## InitDB ### Description Initialize the database connection. ### Method Not specified (Go function signature provided) ### Endpoint Not specified (Go function signature provided) ### Returns: - `error`: Error if initialization fails ### Behavior: - Creates database file if needed - Applies schema migrations - Sets up compression encoders - Validates database format ### Example: ```go if err := storage.InitDB(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### GET /api/v1/message/{id}/sa-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Performs a SpamAssassin check on a specific email message. This requires Mailpit to be started with the `--enable-spamassassin` flag. It returns the spam score, a boolean indicating if it's spam, and the SpamAssassin report. ```APIDOC ## GET /api/v1/message/{id}/sa-check ### Description Check message against SpamAssassin (requires `--enable-spamassassin`). ### Method GET ### Endpoint /api/v1/message/{id}/sa-check ### Response #### Success Response (200 OK) - **score** (number) - The SpamAssassin score. - **is_spam** (boolean) - Indicates if the message is considered spam. - **report** (string) - The full SpamAssassin report. ### Response Example ```json { "score": 2.5, "is_spam": false, "report": "Spam check report text" } ``` ``` -------------------------------- ### Get All Tags in Use Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/storage.md Retrieve a sorted list of all tags currently applied to messages in the mailbox. This function returns a string slice of tag names. ```go tags := storage.GetAllTags() for _, tag := range tags { fmt.Println(tag) } ``` -------------------------------- ### Get Application Information Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Retrieves general information about the Mailpit application, including version, configuration status, and message statistics. Useful for monitoring and diagnostics. ```json { "version": "1.50.0", "mailpit_version": "1.50.0", "is_latest_version": true, "release_notes_link": "https://github.com/axllent/mailpit/releases/latest", "database_type": "sqlite", "demo_mode": false, "ui_auth_enabled": false, "send_api_enabled": true, "chaos_enabled": false, "spamassassin_enabled": false, "stats": { "total_messages": 1234, "read": 1000, "unread": 234 } } ``` -------------------------------- ### Configure Persistent SQLite Database Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Starts Mailpit with a persistent SQLite database file. This ensures emails are stored even after Mailpit restarts. A temporary database is used by default if no path is specified. ```bash # Persistent database mailpit --database /var/lib/mailpit/mail.db # Temporary database (auto-cleanup) mailpit # Uses temp file # Performance options mailpit --compression=3 --max-messages=10000 ``` -------------------------------- ### API Error: 400 Invalid search syntax for GET /api/v1/search Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error occurs when the search query syntax provided to the GET `/api/v1/search` endpoint is malformed. ```json { "error": "Invalid search query syntax" } ``` -------------------------------- ### Start Mailpit with SMTP Relay Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Configures Mailpit to relay all outgoing emails through a specified SMTP server using a configuration file. The configuration file defines the host, port, authentication, and credentials for the relay. ```bash # Create relay.yaml cat > relay.yaml << EOF host: smtp.gmail.com port: 587 starttls: true auth: plain username: sender@gmail.com password: app-password EOF # Start with relay mailpit --smtp-relay-config relay.yaml --smtp-relay-all ``` -------------------------------- ### SMTP Auto-Forward Configuration Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Specifies how to automatically forward all received emails to predefined recipients using an external SMTP server. This YAML configuration includes recipient lists and server connection details. Environment variables offer an alternative configuration method. ```yaml to: admin@example.com,support@example.com host: smtp.example.com port: 587 starttls: true auth: plain username: forwarder@example.com password: password allow-insecure: false return-path: bounce@example.com override-from: mailpit@example.com forward-smtp-errors: false ``` -------------------------------- ### API Error: 400 Invalid message format for GET /api/v1/message/{id}/html-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error is returned by GET `/api/v1/message/{id}/html-check` when the message content cannot be parsed. ```json { "error": "Unable to parse message" } ``` -------------------------------- ### API Error: 503 SpamAssassin not available for GET /api/v1/message/{id}/sa-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error is returned by GET `/api/v1/message/{id}/sa-check` when the SpamAssassin service is unavailable, either due to configuration or network issues. ```json { "error": "SpamAssassin service unavailable" } ``` -------------------------------- ### Enable STARTTLS Support for SMTP Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Enable STARTTLS for SMTP clients by providing certificate and key paths. This allows for encrypted SMTP connections. ```bash mailpit --smtp-tls-cert /etc/ssl/cert.pem \ --smtp-tls-key /etc/ssl/key.pem ``` -------------------------------- ### API Error: 400 Link check not available for GET /api/v1/message/{id}/link-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error indicates that link checking is not configured or available for the requested message via GET `/api/v1/message/{id}/link-check`. ```json { "error": "Link checking not configured" } ``` -------------------------------- ### MessageSummary Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/types.md Provides a summary of a message, intended for listing views where the full content is not required. It includes essential details like sender, subject, and metadata, but omits the message body and full attachments. This type is returned in arrays by `GET /api/v1/messages` and `GET /api/v1/search`. ```APIDOC ## MessageSummary ### Description Summary of a message for listing without full content. ### Fields: - **ID** (string) - Unique database identifier - **MessageID** (string) - RFC 5322 Message-ID - **Read** (bool) - Whether message has been read/viewed - **From** (*mail.Address) - Sender address object - **To** ([]*mail.Address) - Recipient addresses - **Cc** ([]*mail.Address) - Carbon copy addresses - **Bcc** ([]*mail.Address) - Blind carbon copy addresses - **ReplyTo** ([]*mail.Address) - Reply-To addresses - **Subject** (string) - Email subject - **Created** (time.Time) - Received date/time - **Username** (string) - SMTP/API auth username if provided - **Tags** ([]string) - Tags assigned to message - **Size** (uint64) - Message size in bytes - **Attachments** (int) - Number of file attachments - **Snippet** (string) - Text preview up to 250 characters ### Usage in API: Returned in arrays by `GET /api/v1/messages`, `GET /api/v1/search` ``` -------------------------------- ### Configuration Validation: Missing UI TLS certificate or key Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/errors.md This error occurs during startup if both a UI TLS certificate and its corresponding key are not provided when TLS is configured for the UI. ```text [ui] you must provide both a UI TLS certificate and a key ``` -------------------------------- ### Get Mailbox Statistics Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Retrieves statistics for the current mailbox. ```go StatsGet() ``` -------------------------------- ### GET /api/v1/chaos Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves the current chaos mode settings. ```APIDOC ## GET /api/v1/chaos ### Description Retrieves the current chaos mode settings. ### Method GET ### Endpoint /api/v1/chaos ``` -------------------------------- ### SMTP Auto-Relay Configuration Example Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md Defines how to automatically relay outgoing messages through an external SMTP server. This YAML configuration specifies connection details, authentication, and recipient filtering. Alternatively, environment variables can be used. ```yaml host: smtp.gmail.com port: 587 starttls: true auth: plain username: sender@gmail.com password: app-password allow-insecure: false return-path: bounce@example.com override-from: mailpit@example.com allowed-recipients: ".*@allowed-domain.com" blocked-recipients: "admin@.*" preserve-message-ids: false forward-smtp-errors: false ``` -------------------------------- ### GET /api/v1/tags Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves all tags currently applied to messages. ```APIDOC ## GET /api/v1/tags ### Description Retrieves all tags currently applied to messages. ### Method GET ### Endpoint /api/v1/tags ``` -------------------------------- ### ReadyzHandler Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Kubernetes readiness probe endpoint. Checks if the application has finished initialization. ```APIDOC ## GET /readyz ### Description An endpoint to check the readiness of the Mailpit server for Kubernetes probes. It verifies if the application has completed its initialization process. ### Method GET ### Endpoint /readyz ### Parameters None ### Request Example None ### Response #### Success Response (200) Indicates the server is ready. #### Response Example (No specific response body is defined, typically an empty 200 OK status) ``` -------------------------------- ### GET /api/v1/info Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves general information and statistics about the Mailpit application. ```APIDOC ## GET /api/v1/info ### Description Retrieves general information and statistics about the Mailpit application. ### Method GET ### Endpoint /api/v1/info ``` -------------------------------- ### GET /api/v1/message/{id} Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves a specific message by its unique ID. ```APIDOC ## GET /api/v1/message/{id} ### Description Retrieves a specific message by its unique ID. ### Method GET ### Endpoint /api/v1/message/{id} #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### Static Assets Serving Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Serves embedded Web UI files, API documentation, and favicons directly from the compiled binary. ```APIDOC ## Static Assets ### Embedded Files Web UI files are compiled into the binary. ### Handled Routes - `GET /dist/` (JS/CSS/images) - `GET /api/` (API documentation) - `GET /favicon.ico` - `GET /favicon.svg` - `GET /mailpit.svg` - `GET /notification.png` ### Handler `embedController` (serves embedded filesystem) ### Source `server/embed.go` ``` -------------------------------- ### Get All Tags Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Retrieve a list of all tags currently in use within Mailpit. ```json ["tag1", "tag2", "tag3"] ``` -------------------------------- ### GET /api/v1/message/{id}/headers Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves the email headers for a specific message. ```APIDOC ## GET /api/v1/message/{id}/headers ### Description Retrieves the email headers for a specific message. ### Method GET ### Endpoint /api/v1/message/{id}/headers #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### Check UI Authentication Credentials Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md This snippet shows how to verify UI authentication credentials. It checks if UI credentials are configured and then attempts to match the provided username and password. ```go // Check if credentials configured if auth.UICredentials != nil { if auth.UICredentials.Match(username, password) { // Valid } } ``` -------------------------------- ### GET /api/v1/message/{id}/html-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Check HTML email compatibility with email clients. ```APIDOC ## GET /api/v1/message/{id}/html-check ### Description Check HTML email compatibility with email clients. ### Method GET ### Endpoint /api/v1/message/{id}/html-check ### Parameters #### Path Parameters - **id** (string) - Required - Message ID or `latest` ### Response #### Success Response (200 OK) ```json { "score": 9.5, "warnings": [ { "level": "info", "message": "Unsupported CSS property in some clients" } ], "tests": { "html_check": true, "css_support": 0.85 } } ``` ``` -------------------------------- ### GET /api/v1/message/{id}/raw Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Download the raw message in RFC 5322 format. ```APIDOC ## GET /api/v1/message/{id}/raw ### Description Download the raw message (RFC 5322 format). ### Method GET ### Endpoint /api/v1/message/{id}/raw ### Parameters #### Path Parameters - **id** (string) - Required - Message ID or `latest` ### Response #### Success Response (200 OK) Raw email in text/plain format ``` -------------------------------- ### GET /api/v1/message/{id}/raw Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Downloads the raw content of a specific email message. ```APIDOC ## GET /api/v1/message/{id}/raw ### Description Downloads the raw content of a specific email message. ### Method GET ### Endpoint /api/v1/message/{id}/raw #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/smtpd.md A basic Mailpit configuration for development, listening on all interfaces and accepting any authentication. ```bash mailpit \ --smtp=0.0.0.0:1025 \ --listen=0.0.0.0:8025 \ --smtp-auth-accept-any \ --verbose ``` -------------------------------- ### GET /api/v1/messages Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves a list of all messages in the Mailpit inbox. Supports filtering and pagination. ```APIDOC ## GET /api/v1/messages ### Description Retrieves a list of all messages in the Mailpit inbox. Supports filtering and pagination. ### Method GET ### Endpoint /api/v1/messages ``` -------------------------------- ### Paginate Messages Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Retrieves a paginated list of messages based on start point, timestamp, and limit. ```go List(start, beforeTS, limit) ``` -------------------------------- ### GET /api/v1/message/{id}/link-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Checks all links within a specific message for validity and accessibility. ```APIDOC ## GET /api/v1/message/{id}/link-check ### Description Checks all links within a specific message for validity and accessibility. ### Method GET ### Endpoint /api/v1/message/{id}/link-check #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### GET /api/v1/message/{id}/html-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Performs an HTML validation check on the content of a specific message. ```APIDOC ## GET /api/v1/message/{id}/html-check ### Description Performs an HTML validation check on the content of a specific message. ### Method GET ### Endpoint /api/v1/message/{id}/html-check #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### Set General Environment Variables Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/configuration.md Configure general Mailpit settings using environment variables. Ensure the database path is correctly set for persistent storage. ```bash export MP_DATABASE=/var/lib/mailpit/mailpit.db export MP_MAX_MESSAGES=1000 export MP_COMPRESSION=2 ``` -------------------------------- ### GET /api/v1/message/{id}/part/{partID} Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Downloads a specific attachment part of an email message. ```APIDOC ## GET /api/v1/message/{id}/part/{partID} ### Description Downloads a specific attachment part of an email message. ### Method GET ### Endpoint /api/v1/message/{id}/part/{partID} #### Path Parameters - **id** (string) - Required - The unique identifier of the message - **partID** (string) - Required - The identifier of the attachment part ``` -------------------------------- ### Configure Mailpit Authentication Levels Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Demonstrates different levels of authentication configuration for Mailpit, from development (accepting any credentials) to production (requiring specific auth files for UI, SMTP, Send API, and POP3). ```bash # No auth (development) mailpit --smtp-auth-accept-any --send-api-auth-accept-any # Full auth (production) mailpit --ui-auth-file ui.auth \ --smtp-auth-file smtp.auth \ --send-api-auth-file api.auth \ --pop3-auth-file pop3.auth ``` -------------------------------- ### GET /api/v1/message/{id}/sa-check Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Performs a SpamAssassin check on a specific message to assess spam likelihood. ```APIDOC ## GET /api/v1/message/{id}/sa-check ### Description Performs a SpamAssassin check on a specific message to assess spam likelihood. ### Method GET ### Endpoint /api/v1/message/{id}/sa-check #### Path Parameters - **id** (string) - Required - The unique identifier of the message ``` -------------------------------- ### Configure Mailpit Authentication via Command-Line Flags Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Set authentication for UI, Send API, SMTP, and POP3 services using command-line flags. Inline credentials can also be provided directly. ```bash # UI authentication mailpit --ui-auth-file /etc/mailpit/ui.auth # Send API authentication mailpit --send-api-auth-file /etc/mailpit/send-api.auth # SMTP authentication mailpit --smtp-auth-file /etc/mailpit/smtp.auth # POP3 authentication mailpit --pop3-auth-file /etc/mailpit/pop3.auth # Inline credentials mailpit --ui-auth "username:password" mailpit --send-api-auth "api-user:api-password" mailpit --smtp-auth "smtp-user:smtp-password" ``` -------------------------------- ### Wrapping API Handlers with Middleware Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Demonstrates how to apply the core middleware function to protect API endpoints, such as the GetMessages handler. ```go r.HandleFunc("GET /api/v1/messages", middleWareFunc(apiv1.GetMessages)) ``` -------------------------------- ### GET /api/v1/search Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Searches messages based on various criteria. Supports complex queries for filtering results. ```APIDOC ## GET /api/v1/search ### Description Searches messages based on various criteria. Supports complex queries for filtering results. ### Method GET ### Endpoint /api/v1/search ``` -------------------------------- ### Applying Send API Authentication Middleware Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Shows how to wrap the SendMessage handler with the specialized sendAPIAuthMiddleware to enforce Send API credentials. ```go r.HandleFunc("POST /api/v1/send", sendAPIAuthMiddleware(apiv1.SendMessageHandler)) ``` -------------------------------- ### GET /api/v1/messages Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Retrieves a list of messages from the mailbox, ordered from newest to oldest. Supports pagination and filtering by date. ```APIDOC ## GET /api/v1/messages ### Description List messages from the mailbox ordered from newest to oldest. Supports pagination and filtering by date. ### Method GET ### Endpoint /api/v1/messages ### Parameters #### Query Parameters - **start** (integer) - Optional - Pagination offset (default: 0) - **limit** (integer) - Optional - Number of messages to return (default: 50) - **before** (string) - Optional - Return messages before this date (RFC3339 format) ### Response #### Success Response (200 OK) - **total** (integer) - Total number of messages - **unread** (integer) - Number of unread messages - **messages_count** (integer) - Count of messages returned in this request - **messages_unread** (integer) - Count of unread messages returned in this request - **start** (integer) - The pagination offset used - **tags** (array) - List of tags associated with the messages - **messages** (array) - Array of message objects, each containing: - **id** (string) - Unique message identifier - **message_id** (string) - The original email's Message-ID header - **read** (boolean) - Read status of the message - **from** (object) - Sender information (name, address) - **to** (array) - Recipient information - **cc** (array) - CC recipient information - **bcc** (array) - BCC recipient information - **reply_to** (array) - Reply-To recipient information - **subject** (string) - Subject of the email - **created** (string) - Timestamp when the message was created (RFC3339 format) - **username** (string) - Username associated with the message - **tags** (array) - Tags applied to the message - **size** (integer) - Size of the message in bytes - **attachments** (integer) - Number of attachments - **snippet** (string) - A short preview of the email content ### Response Example { "total": 1234, "unread": 5, "messages_count": 1234, "messages_unread": 5, "start": 0, "tags": ["tag1", "tag2"], "messages": [ { "id": "abc123", "message_id": "", "read": false, "from": {"name": "Sender", "address": "sender@example.com"}, "to": [{"name": "Recipient", "address": "recipient@example.com"}], "cc": [], "bcc": [], "reply_to": [], "subject": "Subject", "created": "2024-01-15T10:30:00Z", "username": "user", "tags": ["test"], "size": 1024, "attachments": 2, "snippet": "Email preview text..." } ] } ``` -------------------------------- ### GET /api/v1/message/{id}/part/{partID}/thumb Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/INDEX.md Retrieves a thumbnail preview for a specific attachment part of an email message. ```APIDOC ## GET /api/v1/message/{id}/part/{partID}/thumb ### Description Retrieves a thumbnail preview for a specific attachment part of an email message. ### Method GET ### Endpoint /api/v1/message/{id}/part/{partID}/thumb #### Path Parameters - **id** (string) - Required - The unique identifier of the message - **partID** (string) - Required - The identifier of the attachment part ``` -------------------------------- ### CORS Configuration via Command Line Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/server.md Illustrates how to configure allowed origins for API access using the mailpit command-line flags. Supports single or multiple origins. ```bash # Single origin mailpit --api-cors example.com ``` ```bash # Multiple origins mailpit --api-cors "example.com,foo.com,app.example.org" ``` -------------------------------- ### Configure Mailpit for Development Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/configuration.md Set up Mailpit for development with verbose logging and relaxed authentication for the API and UI. Disabling UI authentication can simplify local testing. ```bash mailpit \ --verbose \ --smtp-auth-accept-any \ --send-api-auth-accept-any \ --ui-auth-file="" ``` -------------------------------- ### Configure SMTP Server Environment Variables Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/configuration.md Configure the SMTP server's bind address and authentication settings using environment variables. ```bash export MP_SMTP_BIND_ADDR=0.0.0.0:1025 export MP_SMTP_AUTH_ACCEPT_ANY=true ``` -------------------------------- ### Configure Send API Authentication File Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/configuration.md Specify the path to the authentication file for the Send API using an environment variable. ```bash export MP_SEND_API_AUTH_FILE=/etc/mailpit/send-api.auth ``` -------------------------------- ### Get Current Chaos Configuration Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Retrieves the current settings for the chaos mode, including whether it is enabled and which specific triggers are active. ```json { "enabled": true, "triggers": [ "rcpt_to_error", "data_error" ] } ``` -------------------------------- ### GET /api/v1/message/{id} Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md Retrieves the complete details of a specific message, identified by its ID. This action also marks the message as read. ```APIDOC ## GET /api/v1/message/{id} ### Description Get the complete message summary, marking the message as read. Use `latest` as the ID to retrieve the most recent message. ### Method GET ### Endpoint /api/v1/message/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Message ID or `latest` ### Response #### Success Response (200 OK) Returns a `Message` object with all message details including full HTML/text body, attachments, and headers. #### Errors - `404 Not Found` if message doesn't exist ``` -------------------------------- ### Search Messages via API Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Searches for messages in Mailpit based on a query parameter. The example filters messages from a specific sender. ```bash curl "http://localhost:8025/api/v1/search?query=from:user@example.com" ``` -------------------------------- ### Production Mailpit Configuration with TLS Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/api-reference/auth.md Sets up Mailpit for production with strict authentication on all services and TLS encryption enabled for SMTP and UI. Requires certificate and key files. ```bash # Strict authentication on all services mailpit \ --ui-auth-file /etc/mailpit/ui.auth \ --smtp-auth-file /etc/mailpit/smtp.auth \ --send-api-auth-file /etc/mailpit/send-api.auth \ --pop3-auth-file /etc/mailpit/pop3.auth \ --smtp-tls-cert /etc/ssl/cert.pem \ --smtp-tls-key /etc/ssl/key.pem \ --smtp-require-starttls \ --ui-tls-cert /etc/ssl/ui-cert.pem \ --ui-tls-key /etc/ssl/ui-key.pem ``` -------------------------------- ### Manage Tags Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/README.md Retrieves all tags, renames a tag, or deletes a tag. ```go GetAllTags() ``` ```go RenameTag(old, new) ``` ```go DeleteTag(tag) ``` -------------------------------- ### Configure SQLite Database Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/configuration.md Specify the path for the SQLite database file. Supports WAL mode, VACUUM for cleanup, and disabling WAL for NFS compatibility. ```bash mailpit --database /var/lib/mailpit/mailpit.db ``` ```bash mailpit --database ./mail.db ``` -------------------------------- ### Get Message Headers Response Structure Source: https://github.com/axllent/mailpit/blob/develop/_autodocs/endpoints.md This JSON object represents the message headers returned by the API. It maps header names to an array of their values. ```json { "Content-Type": ["text/plain; charset=\"UTF-8\""], "Subject": ["Test Subject"], "From": ["sender@example.com"], "To": ["recipient@example.com"] } ```