Wondering what’s next for npm?Check out our public roadmap! »

    TypeScript icon, indicating that this package has built-in type declarations

    12.0.1 • Public • Published

    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.

    Quick links

    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

    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.

    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;
      // get inboxes via import
      const inboxControllerImport = new InboxControllerApi(config);

    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 mx.mailslurp.com 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 @mailslurp.com like so:

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

    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' });

    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 [index, size] = [0, 20];
        const pageInboxes = await mailslurp.getAllInboxes(index, 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(inbox.id);
    const secondEmail = await mailslurp.waitForNthEmail(inbox.id, 1);
    const allEmails = await mailslurp.getInboxEmailsPaginated(inbox.id);

    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: ["test@myemail.com"],
      subject: "Hello",
      body: "Welcome",
    await mailslurp.sendEmail(inbox.id, 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(inbox1.id, {
            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(inbox1.id, { to: [inbox2.emailAddress], subject: "Hello Dogs" })
        await mailslurp.sendEmail(inbox1.id, { to: [inbox2.emailAddress], subject: "Hello Cats" })
        // wait for 2 emails
        const emails = await mailslurp.waitController.waitForEmailCount(2, inbox2.id, timeoutMillis, true)
        const subjects = emails.map(e => 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(inboxId, 30000, true)
        const emailController = new MailSlurp(config).emailController
        const attachmentDto = await emailController.downloadAttachmentBase64(email.attachments[0], email.id)

    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(inbox1.id, { to, subject: "Apples" });
        await mailslurp.sendEmail(inbox1.id, { 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, inbox2.id, 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(inbox1.id, { to, body })
    // wait for email
    const email = await mailslurp.waitController.waitForLatestEmail(inbox2.id, timeoutMillis, true)
    const pattern = "code is: ([0-9]{6})"
    expect(email.body).toContain("Your code is")
    const result = await mailslurp.emailController.getEmailContentMatch({ pattern }, email.id)
    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({
            inboxId: inboxB.id!!,
            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({
            inboxId: inboxA.id,
            unreadOnly: true,
            timeout: 30000,
        // 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.




    npm i mailslurp-client

    DownloadsWeekly Downloads






    Unpacked Size

    2.03 MB

    Total Files


    Last publish


    • avatar