Testing email-related functionality with MailSlurp

Integration testing with disposable email accounts using CypressJS, Selenium and many other frameworks. Test OTP password login, transactional emails, notifications and more.

testing email integration

MailSlurp was built with integration testing as a primary focus. This page covers the basic approaches and use cases.

Quick guides

Jump straight to common testing guides:

Why test with real emails?

Many applications rely on email addresses in some way: for user sign-up, account verification, notifications, communication and more. In order to truly test these features end-to-end one needs access to real email addresses in code. That is what MailSlurp enables: real private inboxes that can send and receive email in applications and tests.

Basics

In testing it is best to create all the entities you need each test run. This ensures that you start with a blank slate each time.

Environments

MailSlurp has a REST API and SDKs in Javascript, PHP, Java, Python, Go and more so it integrates into most test platforms.

Common use cases

In your tests use the inbox's email address if you want to:

  • test that your systems can send emails (and they are valid when received)
  • test that your system can receive emails (and that appropriate actions are taken)
  • test email related processes like user sign-up, password reset, newsletter subscription, transactional emails etc using real email addresses

This guide assumes you have instantiated a Javascript MailSlurp client. For installation see getting started.

Creating inboxes

The first step for any test is to create a new empty inbox with a randomly assigned email address. Use the createInbox() method for this purpose.

const inbox = await mailslurp.createInbox();

The resulting inbox will look something like this:

{
  "id": "123",
  "emailAddress": "123@mailslurp.com"
}

Sending emails

You can send an email easily using the sendEmail() methods with a given inbox id.

await mailslurp.sendEmail(inboxId, { to: [emailAddress], body: 'Hello' });

Receiving emails

To receive emails in tests use the waitFor methods after your app or test has done something that sends an email to your inbox.

waitFor methods hold a connection open until a conditon is met within the default or specified timeout. You must ensure that your test-suite has an appropriately high timeout to permit this.

There are many waitFor methods available. The simplest is waitForLatestEmail which has the following signature:

await mailslurp.waitForLatestEmail(inboxId, timeout, unreadOnly);

Example app

Say you send a welcome email from your application. Image a simple app:

const myApp = {
  async sendWelcomeEmail(emailAddress: string) {
    await mailslurp.sendEmail(config.inboxId, {
      to: [emailAddress],
      subject: 'Welcome!',
    });
  },
};

This will either return the latest email OR hold open the connection until a email is received. You can adjust the timeout period with a millisecond value as the second parameter. Here is an example:

test('our app can send a welcome email', async () => {
  const testInbox = await mailslurp.createInbox();

  await myApp.sendWelcomeEmail(testInbox.emailAddress);

  const welcome = await mailslurp.waitForLatestEmail(testInbox.id, timeout);

  expect(welcome.subject).toBe('Welcome!');
});

Extracting email content

MailSlurp email responses split a message into various properties such as to, subject and body. The body is the text content of an email in string form. The full body is available like so:

const email = await mailslurp.waitForLatestEmail(inbox.id);
console.log(email.body);

If you want to extract a section of the message body for use in further test steps you can do so easily with a regular expression.

await mailslurp.sendEmail(inbox.id, {
  to: [inbox.emailAddress],
  body: 'Hi. Your code is "123456"',
});

// fetch an email
const email = await mailslurp.waitForLatestEmail(inbox.id);

// execute a regular express capture group on the body and
// destructure the matching group into a variable
const [_, verificationCode] =
  /your code is "([0-9]{6})"/gi.exec(email.body) ?? [];
expect(verificationCode).toEqual('123456');

// do something with code like verifying an account
// myApp.confirmUser(verificationCode);

Special characters

Be aware that mail providers sometimes use esoteric SMTP character encodings for common UTF8 characters such as ?, &, and =. MailSlurp tries to correct most of these but if your regex matches aren't finding results you expect on the first attempt try inspecting the body for bad characters. Use HTML entities in your regular expression if this is the case.

Here is an example that extracts a code number from the body of an HTML message containing http://test.com?code=123 from an old mail server.

// notice that "=" is replaced with "=" HTML entity
const [_, code] = /\?code=([^'"]+)/g.exec(body);

Test Framework integrations

MailSlurp is cross-platform and has libraries for many different languages. Here are some notes for popular test frameworks:

CypressJS

MailSlurp works well with Cypress JS meaning you can create email addresses and send and receive email in end-to-end tests. There is even an official Cypress MailSlurp plugin.

It is important to set default timeouts in cypress.json so that MailSlurp's waitFor methods can wait for emails.

{
  "defaultCommandTimeout": 30000,
  "requestTimeout": 30000
}

It is recommended to use MailSlurp with custom Cypress commands. These can be used to wrap MailSlurp's async functions for use with Cypress async style.

For instance, in cypress/support/commands.js:

const mailslurp = new MailSlurp({ apiKey: process.env.API_KEY! });
Cypress.Commands.add('createInbox', () => mailslurp.createInbox());

Then in tests:

cy.createInbox((inbox) => {
cy.get("#sign-up-email").type(inbox.emailAddress);
// etc
    

We recommend using the official MailSlurp Cypress Plugin if you don't want to add methods yourself.

Playwright

Create and control mailboxes in Playwright automated tests using MailSlurps Node, Java, CSharp or Python plugins.

await page.click('[data-test="sign-up-create-account-button"]');
// wait for verification code
const sms = await mailslurp.waitController.waitForLatestSms({
  waitForSingleSmsOptions: {
    phoneNumberId: phone.id,
    unreadOnly: true,
    timeout: 30_000,
  }
})
// extract the confirmation code (so we can confirm the user)
const code = /([0-9]{6})$/.exec(sms.body)?.[1]!!;

Selenium

Selenium email testing is possible with MailSlurp. See our Csharp example or the Java Selenium guide.

/**
 * Create a real email address with MailSlurp and use it to start sign-up on the playground
 */
@Test
public void test3_canCreateEmailAddressAndSignUp() throws ApiException {
    // create a real, randomized email address with MailSlurp to represent a user
    InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
    inbox = inboxControllerApi.createInbox(null,null,null,null,null,null,null, null, null);

    // check the inbox was created
    assertNotNull(inbox.getId());
    assertTrue(inbox.getEmailAddress().contains("@mailslurp.com"));

    // fill the playground app's sign-up form with the MailSlurp
    // email address and a random password
    driver.findElement(By.name("email")).sendKeys(inbox.getEmailAddress());
    driver.findElement(By.name("password")).sendKeys(TEST_PASSWORD);

    // submit the form to trigger the playground's email confirmation process
    // we will need to receive the confirmation email and extract a code
    driver.findElement(By.cssSelector("[data-test=sign-up-create-account-button]")).click();
}

Jest

See the Jest example project.

Related content

Golang email library for sending and reading emails

Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.

NodeJS MailSlurp SDK

Nodemailer alternatives to send and receieve email in code and tests

Email for testing

Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.

The best test email tools compared

How to test transactional email campaigns and email verification using the best free and paid tools.

How to wait for Selenium to start during Codeception tests

Example tutorial for how to wait until webdriver and Selenium have started during Codeception PHP tests

How to test that an email is received using Cypress JS.

Use Cypress JS to test emails are received and validated during end-to-end testing.

Using Email APIs to send and receive emails

Generate dynamic email addresses on demand with MailSlurp - a modern email API.

Email API for email marketing and more

APIs for email marketing and social campaign testing. Send, receive, validate and test emails in code and online.

How to test an email address

Test email accounts for testing email addresses in code or online. Create fake email accounts for testing.

How to start selenium in a background process and wait for it to start

Spawn Selenium server process before tests start for easier acceptance testing.

The ultimate guide to email testing tools

The ultimate guide to email testing tools

Top 3 email testing tools

Top 3 email testing tools

CypressJS Example

Test email sign-up, password verification and more with Cypress JS and MailSlurp. Capture OTP magic links and test auth flows end-to-end.

CypressJS Email Testing

Use real email accounts in CypressJS to test user sign-up, email verification, and more.

Golang mail Library (SMTP)

How to send and receive emails in Go (test email addresses).

Java JVM Examples

Test email sending and receive emails without a mail server.

TestNG Selenium Java Example

Testing user sign up in Java using TestNG and MailSlurp test email accounts

Codeception PHP acceptance testing using real email address APIs

Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp

PHP Email Test Plugins: send and receive email in PHPUnit (example code)

How to send and receive emails in PHPUnit tests.

PyTest Email Testing

Send and receive email in Pytest Python tests.

Java, Selenium

Receive emails in Java test suites using MailSlurp, Junit, and Selenium.

Receive email in PHP: using MailSlurp to send and receive emails

Test email in PHP using real email addresses

Python Robot Framework email test

Python automation email testing Robotframework plugin

Testing authentication using real email addresses in Ruby with Capybara, Cucumber, and Selenium

Cucumber example project using Capybara to test user authentication using real email addresses.

Test applications with real emails using Serenity BDD, JBehave and Selenium

Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.

Specflow user sign-up testing with MailSlurp accounts

How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.

Jest, Puppeteer

Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.

.NET Selenium C#

Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.

Cucumber, Ruby

Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.

Webdriver, JS, WDIO

Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.

TestCafe end-to-end MFA testing for user sign-up and email verification

End-to-end testing with MailSlurp, NodeJS, and TestCafe.

Testing guide

Integration testing with disposable email accounts using CypressJS, Selenium and many other frameworks. Test OTP password login, transactional emails, notifications and more.

How To Test Emails Before You Send

There are many free tools to test emails before sending. This can help prevent spam warnings and increase deliverability.

Testing OTP password link username and password for 2 factor authentication (2FA)

Testing OTP password link username and password for 2 factor authentication (2FA)

Test email address

Free test email address for testing emails online with web dashboard or REST API.

How to test 2FA OTP login using SMS codes with Playwright

The ultimate guide to testing OAuth one-time-password flows with real SMS MFA. Use Playwright to automate authentication tests with programmable TXT message APIs.

Testing email with Cypress test email accounts

Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.

Testing Webhooks

How to test HTTP webhooks using MailSlurp test hooks.

Testing Email with Cypress JS and MailSlurp

Email testing with Cypress JS

Ready to dive in?Start building email applications today.