MailSlurp Javascript Client

Create real email addresses on demand. Send and receive emails and attachments from code and tests using Javascript or Typescript.

MailSlurp is an email API service that lets you create real email addresses in code. You can then send and receive emails and attachments in Javascript applications and tests. Please see the getting started guide for an introduction on key MailSlurp concepts or continue reading.

email testing

Here are some links to get started (or see below for code examples).



Get started

This section describes how to get up and running with the Javascript client.

See the guides page for more examples and use with common frameworks. For use with CypressJS see the official Cypress MailSlurp plugin.

See the method documentation for a list of all functions.

See the test/integration.spec.ts in this package for usage examples of this client.

Create API Key

First you’ll need an API Key. Create a free account and copy the key from your dashboard.


Install NPM dependency

Install MailSlurp using NPM (NodeJS) or by including the source code in your project.

npm install --save mailslurp-client

Import MailSlurp

const MailSlurp = require("mailslurp-client").default;

// or

import { MailSlurp } from "mailslurp-client";

Instantiate a client

Create a MailSlurp instance by instantiating a class with your API Key.

const mailslurp = new MailSlurp({ apiKey: "your_api_key" });

Note the MailSlurp object is a class with many common methods. It does not contain all MailSlurp API methods. The full API is available as individually exported controllers.

See the MailSlurp class documentation for all methods or see the test/integration.spec.ts file for usage examples.

Use individual controllers like so:

// controllers are available on the instance itself or using imports
const { MailSlurp, InboxControllerApi } = require('mailslurp-client');

it('can use inbox controller methods', async () => {
  // inbox actions using instance controllers
  const mailslurp = new MailSlurp(config);
  const inboxController = mailslurp.inboxController;


You can also instantiate controllers directly. See the API controllers for method details.

it('can use inbox controller methods', async () => {
  // get inboxes via import
  const inboxControllerImport = new InboxControllerApi(config);

Fetch and error handling

The MailSlurp client uses fetch to call throws exceptions for non 2xx response status codes.

Configure custom fetch

You can pass the MailSlurp constructor a custom fetch implementation if you wish to control the library used.

const fetchApi = require('isomorphic-fetch') // or window.fetch
const mailslurp = new MailSlurp({ apiKey: process.env.apiKey, fetchApi });

Catch exceptions

Any non-2xx response throws an exception. There are valid 404 responses that you should handle, these include the 404 returned from waitFor methods when the required matching emails could not be found.

  • 4xx (400, 404…) response codes indicate a client error. Access the error message on the response body
  • 5xx (500, 501…) response codes indicate a server error. If encountered please contact support.

Use try{}catch(e){} around MailSlurp methods and use await e.text() to access the exception error message and e.status to access the status code. If you don’t like try catch use the wrapResult helper method to wrap results in a Result<T> type with an error property.

describe("handling mailslurp errors", () => {
  test("try catch and read error", async () => {
    try {
      await mailslurp.inboxController.sendEmailAndConfirm('badInboxId', {})
    } catch (e) {
      // handle the error and status code in your code
      // 404 is returned when emails cannot be found for a given condition for instance
      const message = await e.text();
      const statusCode = e.status;
      // test action
      expect(message).toContain("Invalid ID passed")

Use wrapResult helper

To make exception error handling easier you can call methods using the wrapResult method.

test('can use wrapResult to avoid try catch', async () => {
    // can wrap a bad response and read the error - notice use of anonymous function!
    const res1 = await wrapResult(() => mailslurp.createInboxWithOptions({ emailAddress: 'foo' }))
    expect(res1.error.message).toContain("Invalid ID")

    // can use successful result
    const res2 = await wrapResult(() => mailslurp.createInbox())

Common usage

Here are some snippets of common usage. Read

Create an email address

MailSlurp inboxes have real email addresses. There are several ways to create them. See the docs for full inbox object reference. Inboxes can be either SMTP or HTTP type mailboxes. HTTP inboxes are powered by AWS SES and are great for most use cases. SMTP inboxes use a custom mail server running at to support older email clients. SMTP inboxes are more suitable for public facing usage.

Simple usage

You can create an inbox with a randomly assigned email address ending in like so:

const inbox = await mailslurp.createInbox();
// { id: '123', emailAddress: '' }

Create inbox options

Use the createInboxWithOptions or methods on the inboxController property to create email addresses using more options.

const inbox = await mailslurp.createInboxWithOptions({ inboxType: 'SMTP_INBOX' });

Test example

In a test using Jest:

const MailSlurp = require('mailslurp-client').default;

describe('inbox method usage', () => {
  let config;

  beforeAll(() => {
    // provide a mailslurp API KEY
    const apiKey = process.env.API_KEY;
    // create config for clients and main class
    config = { apiKey };

   * Create an inbox. An inbox is basically an email address. It also has an ID
  it('can create inboxes', async () => {
    const mailslurp = new MailSlurp(config);
    const inbox = await mailslurp.createInbox();

To use custom domains see the domain verification guide

Get an inbox

Inboxes have real email addresses. See the inbox reference for all properties.

 * Get an inbox
it('can get a full inbox', async () => {
    const mailslurp = new MailSlurp(config);
    const { id: inboxId } = await mailslurp.createInbox();
    const inbox = await mailslurp.getInbox(inboxId);

List inboxes

Inbox lists are paginated and sortable. List methods return a projection of an inbox. See the inbox projection reference for properties.

describe("inbox pagination", () => {
   * List inboxes
  it('can list inboxes in paginated form', async () => {
    const mailslurp = new MailSlurp(config);
    // get paginated inboxes
    const [, size] = [0, 20];
    const pageInboxes = await mailslurp.getAllInboxes(, size);


Access controllers

A MailSlurp instance has properties for access all the API endpoints as controllers. See these for further inbox operations.

describe("inbox pagination", () => {
   * Can use inbox controller directly for more advanced usage
   * `const { InboxControllerApi } = require('mailslurp-client');`
  it('can use inbox controller methods', async () => {
    const mailslurp = new MailSlurp(config);
    const inboxController = mailslurp.inboxController;
    const { id: inboxId } = await inboxController.createInbox();
    const { status } = await inboxController.deleteInbox(inboxId)

See method documentation for a list of all functions.

Fetch emails from inbox

To read emails that already exist in an inbox use the EmailController getEmail method. To wait for expected emails that may not have arrived yet use the WaitForController.

There are many ways to receive and fetch emails in MailSlurp. Emails have many properties including body, subject, attachments and more. See the API docs for full email reference.

const latestEmail = await mailslurp.waitForLatestEmail(undefined, undefined,;


const secondEmail = await mailslurp.waitForNthEmail(, 1);
const allEmails = await mailslurp.getInboxEmailsPaginated(;

For more fetching methods see the WaitForController and the EmailController

Send emails

To send emails use the SendEmailOptions arguments with the InboxController or MailSlurp instance methods.

const options = {
  to: [""],
  subject: "Hello",
  body: "Welcome",
await mailslurp.sendEmail(, options);

Upload attachment

Upload attachment using the AttachmentController.

Attachments can be uploaded as base64 strings. The ids returned can the be used with SendEmailOptions send functions. See the upload attachment options for more information.

 * Upload base 64 encoded file
 * Return array containing attachment ID as first element
 * @returns {Promise<string[]>}
async function uploadAttachment() {
    const fileBase64Encoded = await readFile(pathToAttachment, { encoding: 'base64' });
    const attachmentController = new MailSlurp(config).attachmentController;

    return attachmentController.uploadAttachment({
        base64Contents: fileBase64Encoded,
        contentType: 'text/plain',
        filename: basename(pathToAttachment)

Send attachment

To send an attachment first upload the file using the AttachmentController then send an email containing the attachment ID with the InboxController.

You can send attachments by including their IDs in the attachments options when sending.

it("can send attachment", async () => {
    const attachmentIds = await uploadAttachment()

    const inboxController = new MailSlurp(config).inboxController;
    const inbox1 = await inboxController.createInbox();
    const inbox2 = await inboxController.createInbox();

    // send email and get saved result
    const sentEmail = await inboxController.sendEmailAndConfirm(, {
        attachments: attachmentIds,
        subject: "Send attachments",
        body: "Here are your files",
        to: [inbox2.emailAddress]


Wait for multiple emails

The WaitForController contains many methods for waiting for emails to arrive in an inbox. See the waitFor controller reference for more information.

it('can wait for multiple emails', async () => {
    const mailslurp = new MailSlurp(config);

    // example of creating inboxes simultaneously
    const inbox1 = await mailslurp.createInbox();
    const inbox2 = await mailslurp.createInbox();

    // send two emails
    await mailslurp.sendEmail(, { to: [inbox2.emailAddress], subject: "Hello Dogs" })
    await mailslurp.sendEmail(, { to: [inbox2.emailAddress], subject: "Hello Cats" })

    // wait for 2 emails
    const emails = await mailslurp.waitController.waitForEmailCount(2, undefined,, undefined, undefined, timeoutMillis, true)

    const subjects = => e.subject)
    expect(subjects).toContain("Hello Dogs")
    expect(subjects).toContain("Hello Cats")

Receive attachments

To wait for expected emails to arrive and read their contents use the WaitFor controller endpoints.

async function canReceiveAttachment(inboxId) {
    const waitForController = new MailSlurp(config).waitController;

    const email = await waitForController.waitForLatestEmail(undefined, undefined, inboxId, undefined, undefined, 30000, true)


    const emailController = new MailSlurp(config).emailController
    const attachmentDto = await emailController.downloadAttachmentBase64(email.attachments[0],


Wait for matching emails

MailSlurp allows one to wait for emails that match certain parameters. Here is an example:

it('can wait for matching emails', async () => {
    const mailslurp = new MailSlurp(config);

    const inbox1 = await mailslurp.createInbox();
    const inbox2 = await mailslurp.createInbox();

    // specify recipient (must be array)
    const to = [inbox2.emailAddress];

    // send two emails
    await mailslurp.sendEmail(, { to, subject: "Apples" });
    await mailslurp.sendEmail(, { to, subject: "Oranges" });

    // wait for matching email based on subject (see MatchOptions for all options)
    const matchOptions = {
       matches: [
               field: "SUBJECT",
               should: "CONTAIN",
               value: "Apples"
    const expectCount = 1;
    const matchingEmails = await mailslurp.waitController.waitForMatchingEmail(matchOptions, expectCount,, timeoutMillis, true)

See the MatchOptions documentation for reference.

Extract email content

You can extract useful information from emails using regular expressions. See the EmailController for more information:

const mailslurp = new MailSlurp(config);

const inbox1 = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();

const to = [inbox2.emailAddress]
const body = "Hi there. Your code is: 123456"
await mailslurp.sendEmail(, { to, body })

// wait for email
const email = await mailslurp.waitController.waitForLatestEmail(undefined, undefined,, undefined, undefined, timeoutMillis, true)
const pattern = "code is: ([0-9]{6})"
expect(email.body).toContain("Your code is")

const result = await mailslurp.emailController.getEmailContentMatch({ pattern },
expect(result.matches[0]).toEqual("code is: 123456")


You can mask an email address using an alias and the AliasController. An alias is like a proxy. It can receive emails and forward them to any address. You can generate many to one aliases for any email address. You must verify the email address upon first use by clicking a link in the email that is sent to the address. Here is a code example:

 * Example of using an email alias to mask an address and forward emails to hidden address
import 'jest';

import fetchApi from 'isomorphic-fetch';
import {
} from 'mailslurp-admin-sdk';

// setup mailslurp config
const apiKey = process.env.apiKey;
const config = new Configuration({ apiKey, fetchApi });

// create controllers
const inboxControllerApi = new InboxControllerApi(config);
const aliasControllerApi = new AliasControllerApi(config);
const waitForController = new WaitForControllerApi(config);
const emailControllerApi = new EmailControllerApi(config);

// set test timeout to allow wait 

test('aliases', async () => {
    // create two different email addresses for testing
    const inboxA = await inboxControllerApi.createInbox({});
    const inboxB = await inboxControllerApi.createInbox({});
    const emailAddressA = inboxA.emailAddress!!;
    const emailAddressB = inboxB.emailAddress!!;

    // create an alias
    const alias: AliasDto = await aliasControllerApi.createAlias({
        createAliasOptions: {
            emailAddress: emailAddressA,
            useThreads: true,

    // can send email from inboxB to alias that should be delivered to inboxA
    const sent = await inboxControllerApi.sendEmailAndConfirm({
        sendEmailOptions: {
            to: [alias.emailAddress!!],
            subject: 'Hello inbox A',
            body: 'From inbox B',

    // now expect email is forwarded by alias to InboxA
    const forwardedEmail = await waitForController.waitForLatestEmail(
    // received message
    expect(forwardedEmail.subject).toContain('Hello inbox A');
    // reply to is a thread address meaning your replies can be routed through a thread


To have received emails sent to your server using HTTP webhook push create a webhook using the WebhookController or see the webhook email guide.

Create webhooks

mailslurp.webhookController.createWebhook(inboxId, {
    url: "",
    eventName: "NEW_EMAIL"

Listen to webhooks

To consume webhooks first create a webhook for an inbox and a given webhook event. Set the webhook URL to an endpoint on your server. Your server must be publicly accessible and return a 200 or 201 status code in 30 seconds. To test locally use a service like to tunnel your local machine to a public URL. The payload posted to your end point will depend on the event type. Here is a listen example using express

Note: you can use any framework or language you like with webhooks.

const express = require("express");
const app = express.createServer();

 * define your endpoint
 * here your webhook url should include the full protocol and domain.
 * i.e.:
 */"/my-webhook-endpoint", function (request, response) {
  // access the data on request body
  // do something with with inboxId like `mailslurp.waitForLatestEmail(undefined,undefined, inboxId)`

  // return a 2xx status code so MailSlurp knows you received it


Verify email address

You can verify the existence of an email address using the MailServer controller. MailSlurp derives a host for an email address by digging the MX records for the domain. It then connects via telnet to the server and sends the rcpt to:<emailaddress> command to check that the email exists on the server.

describe('can manage smtp inboxes', () => {
    it('can verify an external email address with a provider like gmail', async () => {
        const result = await mailslurp.mailServerController.verifyEmailAddress({
            emailAddress: ""

More Documentation


Feedback, support, and feature requests

The MailSlurp team welcomes any feedback and feature requests. Please use the support portal to report any bugs or speak with support.