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.
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:
- CypressJS Plugin documentation
- CypressJS Plugin source
- CypressJS Javascript
- Robotframework Python
- Cucumber Ruby
- Selenium Java
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 {
logger.info("Create email address");
// create a real, randomized email address with MailSlurp to represent a user
InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
inbox = inboxControllerApi.createInboxWithDefaults();
logger.info("Assert inbox exists");
// check the inbox was created
assertNotNull(inbox.getId());
assertTrue(inbox.getEmailAddress().contains("@mailslurp"));
logger.info("Fill elements");
// 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);
logger.info("Submit sign-up button");
// 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.