MailSlurp Client for Email and SMS API
MailSlurp Client is the official JavaScript and TypeScript library for interacting with the MailSlurp Email and SMS API. It enables developers to programmatically create on-demand email addresses and phone numbers without managing a mail server, facilitating sending and receiving real emails and SMS messages directly from applications or automated tests. The library is currently stable at version 17.2.0 and maintains a regular release cadence. Its key differentiator is providing a fully functional, programmatic interface to an email and SMS infrastructure, making it ideal for robust end-to-end testing of communication workflows. It supports handling attachments, setting custom timeouts for message arrival, and offers both CommonJS and ES module import patterns. The client integrates with the standard `fetch` API and allows for custom `fetch` implementations.
Common errors
-
MailSlurp API Key not found. Please provide an API Key to the MailSlurp client.
cause The `apiKey` option was not provided or was empty when instantiating `new MailSlurp({ apiKey: '...' })`.fixObtain your API Key from the MailSlurp dashboard (app.mailslurp.com) and pass it to the client: `const mailslurp = new MailSlurp({ apiKey: process.env.MAILSLURP_API_KEY });` -
Error: Timeout of 60000ms exceeded
cause An API call, particularly a `waitForController` method, waited longer than the specified timeout for a condition (e.g., email arrival) to be met.fixIncrease the `timeout` parameter for the specific MailSlurp operation, or globally configure the fetch client's timeout. SMTP can be slow, so 60-120 seconds might be necessary for reliability. -
TypeError: (0 , mailslurp_client__WEBPACK_IMPORTED_MODULE_0__.MailSlurp) is not a constructor
cause Incorrect import statement for `MailSlurp` class. This typically indicates a mismatch between the module system being used (CommonJS vs. ESM) and the import syntax.fixFor ES Modules: `import { MailSlurp } from 'mailslurp-client';`. For CommonJS: `const MailSlurp = require('mailslurp-client').default;`.
Warnings
- gotcha MailSlurp API operations, especially waiting for emails (`waitForController`), are designed to hold connections open and require sufficient timeouts. SMTP is an inherently slow protocol, and short timeouts can lead to test failures or unexpected behavior.
- gotcha An API Key is mandatory for all MailSlurp operations. Failing to provide a valid key will result in authentication errors and prevent any API calls from succeeding.
- gotcha The MailSlurp client supports both CommonJS (`require`) and ES Module (`import`) syntax. Developers commonly make mistakes in combining these or using the wrong pattern for their environment, e.g., `require('pkg')` instead of `require('pkg').default` for the main class in CJS.
- gotcha While the client allows overriding the default `fetch` implementation, using a non-standard or incomplete polyfill in Node.js environments can lead to unexpected behavior or missing features compared to a robust solution like `cross-fetch`.
Install
-
npm install mailslurp-client -
yarn add mailslurp-client -
pnpm add mailslurp-client
Imports
- MailSlurp
const MailSlurp = require('mailslurp-client')import { MailSlurp } from 'mailslurp-client' - InboxController
import InboxController from 'mailslurp-client'
import { InboxController } from 'mailslurp-client' - CreateInboxOptions
import type { CreateInboxOptions } from 'mailslurp-client'
Quickstart
import { MailSlurp } from 'mailslurp-client';
// Assuming a test runner like Jest is present for 'expect'
// In a standalone script, you might use console.assert or a custom check.
const expect = (value: any) => ({
toContain: (substring: string) => {
if (typeof value !== 'string' || !value.includes(substring)) {
throw new Error(`Expected "${value}" to contain "${substring}"`);
}
},
toEqual: (expected: any) => {
if (value !== expected) {
throw new Error(`Expected "${value}" to equal "${expected}"`);
}
}
});
async function runMailSlurpExample() {
// Retrieve API Key from environment variables or provide directly
const apiKey = process.env.MAILSLURP_API_KEY ?? 'YOUR_MAILSLURP_API_KEY';
if (apiKey === 'YOUR_MAILSLURP_API_KEY') {
console.warn('WARNING: Replace "YOUR_MAILSLURP_API_KEY" with your actual MailSlurp API Key from mailslurp.com dashboard.');
return;
}
// Create a new MailSlurp client instance
const mailslurp = new MailSlurp({ apiKey });
console.log('Creating a new MailSlurp inbox...');
// Create a new random inbox for testing
const inbox = await mailslurp.inboxController.createInbox({});
console.log(`Inbox created with email address: ${inbox.emailAddress}`);
// Assert that the email address is valid
expect(inbox.emailAddress).toContain('@');
// Example: Send an email from the created inbox
const recipientEmail = 'test-recipient@example.com'; // In a real scenario, this could be another MailSlurp inbox
const emailSubject = 'Hello from MailSlurp!';
await mailslurp.sendController.sendEmailAndConfirm({
inboxId: inbox.id,
sendEmailOptions: {
to: [recipientEmail],
subject: emailSubject,
body: 'This is a test email sent using the MailSlurp client.',
},
});
console.log(`Email sent from ${inbox.emailAddress} to ${recipientEmail}`);
// To demonstrate receiving, let's assume `recipientEmail` is another MailSlurp inbox you control
// Or if sending to itself for loopback test (not typical, but for demonstration):
// const receivedEmail = await mailslurp.waitForController.waitForLatestEmail({
// inboxId: inbox.id,
// timeout: 60000,
// });
// console.log(`Received email with subject: "${receivedEmail.subject}"`);
// expect(receivedEmail.subject).toEqual(emailSubject);
console.log('MailSlurp client initialized and inbox created/sent email. Check your MailSlurp dashboard.');
}
runMailSlurpExample().catch(console.error);