Automated Email Testing in 5 Minutes! Send and receive emails in CI and code.
By: Mailslurp, Email Apis For Developers
Tags: Automation, Continuous Integration, Nodejs, Software Development, DevOps

Email APIs let you create email addresses on demand during automated tests.

Why?

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.

You can create a test in Javascript like so:

npm install --save mailslurp-client

Then instantiate a client:

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

Or with Javascript ES6 style imports (Typescript also supported):

import { MailSlurp } from "mailslurp-client";

Finally, configure the client with a free API Key

const mailSlurp = new MailSlurp({ apiKey: "your_key_here" });

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: ["user@test.com"], 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.

Note: 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:

waitForLatestEmail(inboxId?: string, timeout?: number): Promise<Email>

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('app sends welcome`, async () => {



const inbox = await mailslurp.createInbox();



await myApp.sendWelcome(inbox.emailAddress);



const welcome = await mailslurp.waitForLatestEmail(inbox.id)



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.

// 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})"/g.exec(email.body);



// 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.

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 } = require("mailslurp-client");



Cypress.Commands.add("createInbox", () => {

return mailslurp.createInbox();

});

Then in tests: