Documentation
    Preparing search index...

    Class MailpitEvents

    Client for receiving real-time events from the Mailpit WebSocket API.

    import { MailpitEvents } from "mailpit-ws";
    const events = new MailpitEvents("http://localhost:8025");
    events.onEvent("new", (event) => {
    console.log("New message:", event.Data.Subject);
    });
    Index

    Constructors

    • Creates an instance of MailpitEvents.

      Parameters

      • baseURL: string

        The base URL of the Mailpit instance (e.g. http://localhost:8025).

      • Optionaloptions: MailpitEventsOptions

        Optional configuration.

        Configuration options for a MailpitEvents instance.

        • Optionalauth?: MailpitAuthCredentials

          Optional basic auth credentials.

        • OptionalreconnectOptions?: Omit<Options, "WebSocket">

          Optional reconnection tuning for the underlying ReconnectingWebSocket. Controls retry behaviour, delays, backoff factor, and connection timeout. The WebSocket constructor field is managed internally and cannot be overridden here.

        • OptionalwsOptions?: ClientOptions

          Node.js only Optional options passed to the underlying ws WebSocket constructor. Silently ignored in browsers (native WebSocket has no options object).

      Returns MailpitEvents

      const events = new MailpitEvents("http://localhost:8025");
      
      const events = new MailpitEvents("http://localhost:8025", {
      auth: { username: "admin", password: "supersecret" }
      });
      const events = new MailpitEvents("https://localhost:8025", {
      auth: { username: "admin", password: "supersecret" },
      wsOptions: { rejectUnauthorized: false },
      });

    Methods

    • Connects to the WebSocket endpoint for receiving real-time events.

      Returns Promise<void>

      A Promise that resolves when the WebSocket connection is open.

      Called automatically by onEvent() and waitForEvent().

      Returns a Promise<void> that resolves once the connection is open. Await this before triggering actions that generate events (e.g. sending an email) to avoid the race condition where the event is broadcast before the socket is ready:

      // Register the listener first so no events are missed during the connection phase
      const eventPromise = events.waitForEvent("new");
      // Then ensure the socket is open before triggering the action
      await events.connect();
      await mailpit.sendMessage({ ... });
      const event = await eventPromise;

      If the socket is already open the returned Promise resolves immediately.

    • Disconnects from the real-time event stream.

      Returns void

      events.disconnect();
      
    • Registers a listener for real-time events of a specific type.

      Type Parameters

      Parameters

      • eventType: T

        The type of event to listen for. Specific event types include: "new" (new messages), "stats", "update", "delete", "prune", "truncate", and "error". Use "*" to listen for all event types (Useful if processing all events uniformly (e.g., logging, debugging, metrics)).

      • listener: (event: MailpitEventMap[T]) => void

        The callback function to invoke when an event is received

      Returns () => void

      A function to unregister the listener

      Automatically connects to the event stream if not already connected.

      Browser only WebSocket limitation: The connection will fail if Mailpit requires authentication and no other mechanism (e.g. a reverse proxy that injects credentials, or cached browser credentials from a prior UI login) is in place. This limitation does NOT affect Node.js. In Node, auth headers are sent correctly for both HTTP and WebSocket connections.

      const unsubscribe = events.onEvent("new", (event) => {
      // event.Data is typed as MailpitMessageListItem with full type safety
      console.log("New message:", event.Data.Subject);
      });

      // Ensure the socket is open before triggering any action that generates events.
      // onEvent() auto-connects, but the handshake is async - events broadcast before
      // the socket is open will be silently lost.
      await events.connect();

      // Other code that triggers events...

      // Unsubscribe listener when no longer needed
      unsubscribe();
      const unsubscribe = events.onEvent("*", (event) => {
      // Generic processing for all event types
      console.log(`Event ${event.Type} received`);
      });

      await events.connect();

      // Other code...

      // Unsubscribe listener when no longer needed
      unsubscribe();
    • Waits for the next event of a specific type.

      Type Parameters

      • T extends "new" | "stats" | "update" | "delete" | "prune" | "truncate" | "error"

      Parameters

      • eventType: T

        The type of event to wait for. Specific event types include: "new" (new messages), "stats", "update", "delete", "prune", "truncate", and "error".

      • timeout: number = 5_000

        Timeout in milliseconds (default: 5000ms). Pass Infinity to disable timeout.

      Returns Promise<MailpitEventMap[T]>

      A promise that resolves with the event when received, or rejects on timeout

      Automatically connects to the event stream if not already connected. Primarily intended for testing scenarios where you need to wait for a single specific event. The promise will reject if the timeout is reached before an event is received.

      Browser only WebSocket limitation: The connection will fail if Mailpit requires authentication and no other mechanism (e.g. a reverse proxy that injects credentials, or cached browser credentials from a prior UI login) is in place. This limitation does NOT affect Node.js. In Node, auth headers are sent correctly for both HTTP and WebSocket connections.

      // Register the listener first so no events are missed
      const eventPromise = events.waitForEvent("new");

      // Ensure the socket is open before triggering the action.
      // waitForEvent() auto-connects, but the handshake is async - if you trigger
      // an action before the socket is open, the event may be broadcast and lost.
      await events.connect();

      // Do something that triggers an email to send
      await mailpit.sendMessage({
      From: { Email: "test@example.test" },
      To: [{ Email: "recipient@example.test" }],
      Subject: "Test",
      });

      // Wait for the event confirming the message was received
      const event = await eventPromise;
      // event.Data is fully typed as MailpitMessageListItem
      console.log("Message received:", event.Data.Subject);