Registry / testing / mailpit-api

mailpit-api

JSON →
library1.9.0jsnpmunverified

The `mailpit-api` package provides a robust TypeScript client for programmatically interacting with the Mailpit REST API. It enables developers to automate email testing workflows in various JavaScript environments, including Node.js, browsers, and modern JS runtimes, making it ideal for end-to-end (E2E) testing with frameworks like Playwright. The current stable version is 1.9.0, with minor releases and patch fixes occurring frequently, often driven by dependency updates and feature enhancements such as WebSocket support for real-time event listening. Key differentiators include its TypeScript-first design, comprehensive documentation, and specific utilities for common testing scenarios like waiting for messages to arrive, clearing mailboxes, and inspecting email content, all while maintaining compatibility across diverse JavaScript ecosystems. It simplifies the integration of email verification into automated test suites by abstracting the raw Mailpit API calls.

npm install mailpit-api
INSTALL
IMPORT
SIG · MAILPIT-API
M
mailpit-api
testingjavascriptv1.9.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MailpitClient
import { MailpitClient } from 'mailpit-api';
const { MailpitClient } = require('mailpit-api');
Primary class for interacting with the Mailpit API. While CommonJS `require` might work in some environments, ESM is the recommended and best-supported import method for this TypeScript-first library.
MailpitMessage
import type { MailpitMessage } from 'mailpit-api';
import { MailpitMessage } from 'mailpit-api';
Import types using `import type` for better type safety and to avoid bundling issues in some environments. `MailpitMessage` is a common interface for email objects.
waitForMessage
const message = await mailpit.waitForMessage({ query: 'subject:Test' });
import { waitForMessage } from 'mailpit-api';
`waitForMessage` and `waitForMessages` are methods of the `MailpitClient` instance, not top-level exports. Access them via an initialized client object.

This quickstart demonstrates how to initialize the `MailpitClient`, clear existing emails, simulate sending an email to Mailpit, wait for a specific email to be received, and perform basic assertions on its content. It includes setup for a local Mailpit instance and uses `expect` for illustrative assertions.

import { MailpitClient } from "mailpit-api"; import { expect } from "@playwright/test"; // Assuming Mailpit is running on default port 8025 const MAILPIT_URL = process.env.MAILPIT_BASE_URL ?? "http://localhost:8025"; const mailpit = new MailpitClient(MAILPIT_URL); async function runMailpitExample() { // 1. Clean up any previous messages await mailpit.deleteMessages(); console.log("All existing messages deleted."); // 2. Simulate sending an email (this would typically be done by your application under test) // For demonstration, we'll use a mock 'sendMessage' if your app doesn't have an SMTP client exposed. // In a real E2E test, your app would send an email that Mailpit intercepts. // Example of a direct API call (not typical for E2E, but shows capability): // await mailpit.sendEmail({ /* Mailpit's internal send endpoint */ }); // --- Simulate an email being sent to Mailpit (e.g., via your app) --- // For a real test, you'd trigger your app to send an email here. // We'll manually inject one for this quickstart's sake: await mailpit.createMessage({ From: { Email: "sender@example.com", Name: "Test Sender" }, To: [{ Email: "recipient@example.com", Name: "Test Recipient" }], Subject: "Welcome to Mailpit API Client!", HTML: "<p>Hello from Mailpit!</p>", Text: "Hello from Mailpit!", Headers: { "X-Test-Header": "Example" } }); console.log("Simulated email sent to Mailpit."); // 3. Wait for the specific message to appear in Mailpit const receivedMessage = await mailpit.waitForMessage({ query: "subject:\"Welcome to Mailpit API Client!\"", timeout: 10000 // Wait up to 10 seconds }); console.log("Received message:", receivedMessage.Subject); // 4. Perform assertions on the received message expect(receivedMessage).toBeDefined(); expect(receivedMessage.Subject).toEqual("Welcome to Mailpit API Client!"); expect(receivedMessage.To[0].Address).toEqual("recipient@example.com"); expect(receivedMessage.From.Address).toEqual("sender@example.com"); // 5. Optionally, retrieve all messages and verify count const allMessages = await mailpit.listMessages(); expect(allMessages.length).toBeGreaterThanOrEqual(1); console.log(`Currently ${allMessages.length} messages in Mailpit.`); // 6. Disconnect from WebSocket if used (for persistent connections) mailpit.disconnect(); console.log("Mailpit client disconnected."); } runMailpitExample().catch(error => { console.error("Mailpit example failed:", error); process.exit(1); });
Debug
Known issues
breakingPrior to v1.8.1, there were issues with the `package.json` `exports` and `main` fields, which could lead to import errors, especially in environments with strict module resolution or hybrid ESM/CJS setups. This was fixed to ensure broader compatibility.
fix
Update to version `1.8.1` or newer: `npm install mailpit-api@latest`.
affects: <1.8.1
gotchaWebSocket functionality for real-time events (introduced in v1.6.0) initially faced compatibility issues in different JavaScript runtimes due to direct `ws` imports. This was addressed by switching to `partysocket/ws` and `isomorphic-ws` for broader compatibility.
fix
Ensure you are on `mailpit-api@1.8.0` or higher to benefit from improved WebSocket stability and compatibility. If using WebSocket features with older versions, manual polyfills or specific environment configurations might be necessary.
affects: >=1.6.0 <1.8.0
gotchaThe `MailpitClient` constructor now accepts an optional third parameter for `AxiosRequestConfig` (minus `baseURL`, `auth`, `validateStatus`), allowing for custom Axios configuration. If you were passing an unlisted configuration property directly to the constructor in older versions and expecting it to be passed to Axios, this explicit option is now available.
fix
When initializing `MailpitClient`, pass Axios configuration options as the third argument (e.g., `new MailpitClient(baseUrl, undefined, { timeout: 5000 })`). Review the `CreateAxiosDefaults` type for allowed properties.
affects: >=1.9.0
gotchaWebSocket methods like `waitForMessage` and `waitForMessages` (introduced in v1.8.0) require a connected WebSocket. Ensure `mailpit.connect()` is called if using these methods for long-lived or event-driven scenarios, though the methods might handle implicit connection.
fix
For explicit control over WebSocket lifecycle, call `mailpit.connect()` and `mailpit.disconnect()` as needed, especially in test teardown phases.
affects: >=1.8.0
Errors
Common errors & fixes
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'mailpit-api' imported from ...
Incorrect module resolution due to `package.json` export issues or attempting CommonJS `require` in an ESM context.
fix
Update `mailpit-api` to v1.8.1 or newer. Ensure your project is configured for ESM imports if using `import { MailpitClient } from 'mailpit-api';` and running in Node.js >=12, or stick to CommonJS `require` if your project is purely CJS and the library correctly supports it (which is less guaranteed for modern TS libraries).
TypeError: Cannot read properties of undefined (reading 'disconnect')
Attempting to call `disconnect()` on a `MailpitClient` instance that was not properly initialized or has already been garbage collected/reset in a test fixture.
fix
Ensure the `mailpit` client instance is within scope and properly initialized before calling `disconnect()`. In Playwright fixtures, ensure `mailpit.disconnect()` is called in the `teardown` phase after `use(mailpit)`.
UnhandledPromiseRejectionWarning: AxiosError: Network Error
The Mailpit server is not running or is inaccessible at the provided `baseURL`, or there's a network issue preventing the client from connecting.
fix
Verify that your Mailpit instance is running and accessible from where your client code is executing. Double-check the `baseURL` passed to the `MailpitClient` constructor (e.g., `http://localhost:8025`). Check firewall settings if applicable.
Upgrade
Version history
1.9.0latest on npm
Audit
Dependencies
axiosrequiredHTTP client for making API requests to Mailpit.
partysocketrequiredProvides WebSocket functionality for real-time Mailpit events, addressing cross-environment compatibility issues.
isomorphic-wsrequiredImproved WebSocket compatibility across different JS runtimes (added in v1.8.0).
Agent activity
15 hits · last 30 days
node
12
OpenAI (training)
1
Resources
mailpit-api — npm install mailpit-api · libregistry