{"id":13501,"library":"mailpit-api","title":"Mailpit API Client","description":"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.","status":"active","version":"1.9.0","language":"javascript","source_language":"en","source_url":"https://github.com/mpspahr/mailpit-api","tags":["javascript","mailpit","api","client","email","smtp","typescript","test","playwright"],"install":[{"cmd":"npm install mailpit-api","lang":"bash","label":"npm"},{"cmd":"yarn add mailpit-api","lang":"bash","label":"yarn"},{"cmd":"pnpm add mailpit-api","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"HTTP client for making API requests to Mailpit.","package":"axios","optional":false},{"reason":"Provides WebSocket functionality for real-time Mailpit events, addressing cross-environment compatibility issues.","package":"partysocket","optional":false},{"reason":"Improved WebSocket compatibility across different JS runtimes (added in v1.8.0).","package":"isomorphic-ws","optional":false}],"imports":[{"note":"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.","wrong":"const { MailpitClient } = require('mailpit-api');","symbol":"MailpitClient","correct":"import { MailpitClient } from 'mailpit-api';"},{"note":"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.","wrong":"import { MailpitMessage } from 'mailpit-api';","symbol":"MailpitMessage","correct":"import type { MailpitMessage } from 'mailpit-api';"},{"note":"`waitForMessage` and `waitForMessages` are methods of the `MailpitClient` instance, not top-level exports. Access them via an initialized client object.","wrong":"import { waitForMessage } from 'mailpit-api';","symbol":"waitForMessage","correct":"const message = await mailpit.waitForMessage({ query: 'subject:Test' });"}],"quickstart":{"code":"import { MailpitClient } from \"mailpit-api\";\nimport { expect } from \"@playwright/test\";\n\n// Assuming Mailpit is running on default port 8025\nconst MAILPIT_URL = process.env.MAILPIT_BASE_URL ?? \"http://localhost:8025\";\nconst mailpit = new MailpitClient(MAILPIT_URL);\n\nasync function runMailpitExample() {\n  // 1. Clean up any previous messages\n  await mailpit.deleteMessages();\n  console.log(\"All existing messages deleted.\");\n\n  // 2. Simulate sending an email (this would typically be done by your application under test)\n  // For demonstration, we'll use a mock 'sendMessage' if your app doesn't have an SMTP client exposed.\n  // In a real E2E test, your app would send an email that Mailpit intercepts.\n  // Example of a direct API call (not typical for E2E, but shows capability):\n  // await mailpit.sendEmail({ /* Mailpit's internal send endpoint */ });\n\n  // --- Simulate an email being sent to Mailpit (e.g., via your app) ---\n  // For a real test, you'd trigger your app to send an email here.\n  // We'll manually inject one for this quickstart's sake:\n  await mailpit.createMessage({\n    From: { Email: \"sender@example.com\", Name: \"Test Sender\" },\n    To: [{ Email: \"recipient@example.com\", Name: \"Test Recipient\" }],\n    Subject: \"Welcome to Mailpit API Client!\",\n    HTML: \"<p>Hello from Mailpit!</p>\",\n    Text: \"Hello from Mailpit!\",\n    Headers: { \"X-Test-Header\": \"Example\" }\n  });\n\n  console.log(\"Simulated email sent to Mailpit.\");\n\n  // 3. Wait for the specific message to appear in Mailpit\n  const receivedMessage = await mailpit.waitForMessage({\n    query: \"subject:\\\"Welcome to Mailpit API Client!\\\"\",\n    timeout: 10000 // Wait up to 10 seconds\n  });\n\n  console.log(\"Received message:\", receivedMessage.Subject);\n\n  // 4. Perform assertions on the received message\n  expect(receivedMessage).toBeDefined();\n  expect(receivedMessage.Subject).toEqual(\"Welcome to Mailpit API Client!\");\n  expect(receivedMessage.To[0].Address).toEqual(\"recipient@example.com\");\n  expect(receivedMessage.From.Address).toEqual(\"sender@example.com\");\n\n  // 5. Optionally, retrieve all messages and verify count\n  const allMessages = await mailpit.listMessages();\n  expect(allMessages.length).toBeGreaterThanOrEqual(1);\n  console.log(`Currently ${allMessages.length} messages in Mailpit.`);\n\n  // 6. Disconnect from WebSocket if used (for persistent connections)\n  mailpit.disconnect();\n  console.log(\"Mailpit client disconnected.\");\n}\n\nrunMailpitExample().catch(error => {\n  console.error(\"Mailpit example failed:\", error);\n  process.exit(1);\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Update to version `1.8.1` or newer: `npm install mailpit-api@latest`.","message":"Prior 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.","severity":"breaking","affected_versions":"<1.8.1"},{"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.","message":"WebSocket 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.","severity":"gotcha","affected_versions":">=1.6.0 <1.8.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.9.0"},{"fix":"For explicit control over WebSocket lifecycle, call `mailpit.connect()` and `mailpit.disconnect()` as needed, especially in test teardown phases.","message":"WebSocket 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.","severity":"gotcha","affected_versions":">=1.8.0"}],"env_vars":null,"search_vec":"'1.9.0':60 'abstract':136 'across':120 'api':2,7,21,140,144 'arriv':109 'autom':26,132 'browser':36 'call':141 'clear':110 'client':3,13,145 'common':101 'compat':119 'comprehens':95 'content':115 'current':56 'depend':72 'design':94 'develop':24 'differenti':88 'divers':121 'document':96 'driven':70 'e2e':49 'ecosystem':123 'email':27,114,129,146 'enabl':23 'end':46,48 'end-to-end':45 'enhanc':76 'environ':33 'event':85 'featur':75 'first':93 'fix':66 'framework':52 'frequent':68 'ideal':43 'includ':34,89 'inspect':113 'integr':127 'interact':16 'javascript':32,122,142 'js':39 'key':87 'like':53,104 'listen':86 'mailbox':111 'mailpit':1,6,19,139,143 'mailpit-api':5 'maintain':118 'make':41 'messag':107 'minor':62 'modern':38 'node.js':35 'occur':67 'often':69 'packag':8 'patch':65 'playwright':54,150 'programmat':15 'provid':9 'raw':138 'real':83 'real-tim':82 'releas':63 'rest':20 'robust':11 'runtim':40 'scenario':103 'simplifi':125 'smtp':147 'specif':98 'stabl':57 'suit':134 'support':80 'test':28,50,102,133,149 'time':84 'typescript':12,92,148 'typescript-first':91 'updat':73 'util':99 'various':31 'verif':130 'version':58 'wait':105 'websocket':79 'workflow':29","created_at":"2026-04-20T01:54:49.728899+00:00","updated_at":"2026-04-20T01:54:49.728899+00:00","problems":[{"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).","cause":"Incorrect module resolution due to `package.json` export issues or attempting CommonJS `require` in an ESM context.","error":"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'mailpit-api' imported from ..."},{"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)`.","cause":"Attempting to call `disconnect()` on a `MailpitClient` instance that was not properly initialized or has already been garbage collected/reset in a test fixture.","error":"TypeError: Cannot read properties of undefined (reading 'disconnect')"},{"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.","cause":"The Mailpit server is not running or is inaccessible at the provided `baseURL`, or there's a network issue preventing the client from connecting.","error":"UnhandledPromiseRejectionWarning: AxiosError: Network Error"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":"https://mailpit.axllent.org","github":"https://github.com/mpspahr/mailpit-api","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/mailpit-api","openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing","http-networking","communication"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}