smtp4dev Documentation

repository·master·Indexed 26 days ago

https://github.com/rnwood/smtp4dev

A fake SMTP email server for development and testing on Windows, Linux, and Mac OS-X. It provides tools for inspecting, validating, and simulating email delivery via a web UI, TUI, and an OpenAPI-compliant REST API. Features include support for IMAP and POP3, TLS/SSL encryption, XOAUTH2 authentication, and a fluent Builder API for C# integration.

Tokens
28.7K
Snippets
43
Records
107
Agent score
84%

What's inside smtp4dev

  1. Overview of smtp4dev features

    master

    smtp4dev is a dummy SMTP server designed for development and testing on Windows, Linux, and Mac OS-X (where .NET Core is available). It allows you to test email functionality without sending real emails to customers.

    Key features include:

    • API Access: OpenAPI/Swagger supported.
    • Protocols: SMTP server, IMAP, and POP3 access for retrieving/deleting messages.
    • UI Modes: Advanced Web Interface and a full-featured Terminal User Interface (TUI).
    • Email Inspection: Multipart MIME inspector, HTML compatibility reports, HTML validation, and raw message source viewing with syntax highlighting.
    • Testing Capabilities: Viewport size switcher for responsive design testing, SMTP session logging, and scripting expressions for error simulation.
    • Security & Auth: TLS/SSL (implicit and STARTTLS) with auto self-signed cert generation, and authentication support.
    • Management: Multiple mailboxes with routing rules, and message relay/composition capabilities.
  2. Use smtp4dev with Java Testcontainers

    master

    You can run smtp4dev in automated Java tests using Testcontainers. This involves pulling the rnwood/smtp4dev:v3 image, exposing ports 80 (Web), 25 (SMTP), and 143 (IMAP), and configuring the ServerOptions__Urls environment variable to ensure the web server is accessible. You can then verify captured emails by querying the /api/messages endpoint.

    import org.testcontainers.containers.GenericContainer;
    import org.testcontainers.containers.wait.strategy.Wait;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.AfterEach;
    
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.net.URI;
    import java.util.Properties;
    
    public class SmtpTestcontainersTest {
        
        private GenericContainer<?> smtp4dev;
        private HttpClient httpClient;
        private String baseUrl;
        private int smtpPort;
    
        @BeforeEach
        void setUp() {
            smtp4dev = new GenericContainer<>("rnwood/smtp4dev:v3")
                    .withExposedPorts(80, 25, 143)
                    .withEnv("ServerOptions__Urls", "http://*:80")
                    .waitingFor(Wait.forHttp("/").forPort(80));
            
            smtp4dev.start();
            
            int webPort = smtp4dev.getMappedPort(80);
            smtpPort = smtp4dev.getMappedPort(25);
            baseUrl = "http://localhost:" + webPort;
            
            httpClient = HttpClient.newHttpClient();
        }
    
        @Test
        void testEmailCapture() throws Exception {
            // Send email via SMTP
            Properties props = new Properties();
            props.put("mail.smtp.host", "localhost");
            props.put("mail.smtp.port", smtpPort);
            
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("test@example.com"));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
            message.setSubject("Test Subject");
            message.setText("Test Body");
            
            Transport.send(message);
            
            // Wait and check API
            Thread.sleep(1000);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl + "/api/messages"))
                    .build();
            
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            assert response.body().contains("Test Subject");
        }
    
        @AfterEach
        void tearDown() {
            if (smtp4dev != null) {
                smtp4dev.stop();
            }
        }
    }
  3. Access the interactive smtp4dev API documentation

    master
    When smtp4dev is running, you can access the complete API documentation, including interactive examples and detailed endpoint specifications, by navigating to the /api endpoint on your running instance.
  4. Run smtp4dev with the Terminal User Interface (TUI)

    master

    To launch smtp4dev using its comprehensive Terminal User Interface, use the --tui flag. You can also specify custom ports for SMTP and IMAP during startup.

    Key features available in TUI mode include:

    • Editable settings with persistence
    • Enhanced MIME parts tree view
    • Mailbox and folder navigation
    • Search and filtering for messages and sessions
    • Terminal-friendly HTML rendering
    • Split-screen dual-panel views
    • Real-time auto-refresh (every 2-3 seconds)
    • User and Mailbox management
    smtp4dev --tui --smtpport=2525 --imapport=1143
  5. Download smtp4dev standalone binaries

    master

    You can download standalone releases from GitHub. Choose the binary based on your operating system and architecture:

    PrefixDescription
    Rnwood.Smtp4dev-win-x64Windows x64 (Intel 64 bit) binary standalone
    Rnwood.Smtp4dev-noruntimeArchitecture dependent. Requires .NET 10+ runtime
    Rnwood.Smtp4dev-linux-x64Linux x64 (Intel 64 bit) binary standalone
    Rnwood.Smtp4dev-linux-musl-x64Linux x64 (Intel 64 bit) binary standalone for MUSL based distros (Alpine Linux)
    Rnwood.Smtp4dev-linux-armLinux ARM (Intel 32 bit) binary standalone
    Rnwood.Smtp4dev-win-armWindows ARM 32-bit binary standalone

    Running the binaries:

    • Linux: Run chmod +x Rnwood.Smtp4dev to make the file executable.
    • Configuration: Edit appsettings.json to set the SMTP server port.
    • Execution: Run Rnwood.Smtp4dev (or .exe on Windows). If using the noruntime version, execute dotnet Rnwood.Smtp4dev.dll.
  6. Integrate smtp4dev into automated tests

    master

    smtp4dev can be integrated into automated testing workflows using several methods:

    • REST API: Run smtp4dev programmatically and interact with captured messages via HTTP.
    • SignalR: Subscribe to real-time email notifications as they arrive.
    • Testcontainers: Use Testcontainers to manage smtp4dev instances across multiple programming languages.
    • Direct SMTP Component: Use the direct SMTP server component within .NET applications.

    For detailed implementation examples and best practices, refer to the Testing Guide.

  7. Quick Start: OAuth2/XOAUTH2 Demo with JHipster Registry

    master

    This guide walks through running the end-to-end OAuth2 demo using Docker Compose.

    1. Start the services: Run docker-compose up -d to start JHipster Registry and smtp4dev.
    2. Wait for readiness: Ensure JHipster Registry is healthy (via /management/health) and smtp4dev is responding on its API endpoint.
    3. Run the test script: Execute python3 test_oauth2.py to automate token acquisition, SMTP authentication, and email sending.
    4. Verify results: Check the smtp4dev Web UI at http://localhost:5000 to see the received email.
    # 1. Start services
    docker-compose up -d
    
    # 2. Wait for JHipster Registry
    until curl -sf http://localhost:8761/management/health > /dev/null; do
        echo "Waiting for JHipster Registry..."
        sleep 5
    done
    
    # 2b. Wait for smtp4dev
    until curl -sf http://localhost:5000/api/server > /dev/null; do
        echo "Waiting for smtp4dev..."
        sleep 2
    done
    
    # 3. Run test script
    python3 test_oauth2.py
  8. Run the Memory Leak Stress Test

    master

    You can run stress tests to validate memory stability and ensure that search operations do not cause memory leaks under high load. There are two primary test scenarios available via the .NET CLI.

    Prerequisites

    • .NET 10.0 SDK
    • Available ports for SMTP (2525) and HTTP (5000) services

    Test Scenarios

    1. Full Stress Test: A 2-minute test simulating 1,000 messages with 5 concurrent SMTP senders and 3 concurrent API readers. Use this for deep validation.
    2. Quick CI Test: A 30-second test designed for CI/CD environments with reduced load (150 messages, 2 concurrent senders/readers).

    Execution

    Use the dotnet test command with a filter to select the desired test.

    # Run the full stress test
    dotnet test --filter "FullyQualifiedName~MessageSearchStressTest_ShouldNotLeakMemory"
    
    # Run the quick CI test
    dotnet test --filter "FullyQualifiedName~MessageSearchStressTest_QuickCI_ShouldNotLeakMemory"
  9. Manage smtp4dev configuration files

    master

    smtp4dev uses two types of configuration files. To prevent your custom settings from being overwritten during updates, you should use a 'user' configuration file instead of modifying the default one.

    1. Default settings file: Located at <installlocation>/appsettings.json. This file is included in every release and is overwritten during updates.
    2. User settings file: Located at {AppData}/smtp4dev/appsettings.json. This is the recommended location for customisations.

    Platform-specific {AppData} locations:

    • Windows: Use the APPDATA environment variable.
    • Linux & Mac: Use the XDG_CONFIG_HOME environment variable.

    When smtp4dev starts, it prints the search path for these files to the console. You can check the startup logs to find the exact paths being used.

    smtp4dev version 3.3.6...
    Install location: C:\Users\rob
    DataDir: C:\Users\rob\AppData\Roaming\smtp4dev
    Default settings file: ...\appsettings.json
    User settings file: C:\Users\rob\AppData\Roaming\smtp4dev\appsettings.json