Skip to main content

Waiting for matching entities

How to wait and search for matching emails, TXT messages, and events.

Waiting for messages

MailSlurp provides convenient methods for waiting for emails, SMS, and events to arrive. You can use these methods to wait for messages to arrive in tests or to wait for messages to arrive in production applications. You can also match based on the message content or metadata.

Examples

Here are examples of how to fetch emails in code.

Creating a client

First install a MailSlurp SDK for your language. Then create a client instance using your API key. You can find your API key on the MailSlurp dashboard.

const {MailSlurp} = await import("mailslurp-client");
const mailslurp = new MailSlurp({
apiKey: YOUR_API_KEY
});
const inbox = await mailslurp.createInboxWithOptions({
// expires in 5 minutes
expiresIn: 300_000
});
expect(inbox.emailAddress).toContain("@mailslurp");

Wait for latest email

The default wait method is to wait for the latest email. This means the first email matching the conditions. The client will hold a connection until the conditions are met.

// send an email
await mailslurp.inboxController.sendEmailAndConfirm({
inboxId: inbox.id,
sendEmailOptions: {
to: [inbox.emailAddress],
subject: "First email",
}
})
// wait for the first unread email to arrive
const email = await mailslurp.waitController.waitForLatestEmail({
timeout: 120_000,
inboxId: inbox.id,
unreadOnly: true
})
expect(email.subject).toContain('First email')

In this example we create an inbox and then send an email from it to itself. Next we wait for the email to arrive and make assertions about its subject.

Wait for matching emails

A more complex example is to wait fo messages that match particular criteria, such as subject line.

// send two emails
for (const i of [1, 2]) {
await mailslurp.inboxController.sendEmailAndConfirm({
inboxId: inbox.id,
sendEmailOptions: {
to: [inbox.emailAddress],
// send a different message each time
subject: `Match subject test-${i}`,
}
})
}
// wait for 2 emails matching the subject with a pattern
const emails = await mailslurp.waitController.waitForMatchingEmails({
inboxId: inbox.id,
timeout: 120_000,
unreadOnly: true,
count: 2,
matchOptions: {
matches: [
{
// expect subject to contain "Match subject"
value: "Match subject",
field: MatchOptionFieldEnum.SUBJECT,
should: MatchOptionShouldEnum.CONTAIN
}
]
}
})
// assert we received two emails matching the subject
expect(emails.length).toEqual(2)
// the subjects contain the test number from the loop
expect(emails.filter(it => it.subject.includes("Match subject test-1")).length).toEqual(1)

Wait for email number

We can also wait for the "nth" email, an email at a particular index. This is useful for testing pagination or other scenarios where you want to wait for a particular email.