Waiting for matching email content

MailSlurp provides many API endpoints for waiting for emails and extracting their content. It also provides search and pattern matching features. These are designed to work with the unpredictable nature of email: emails may not always arrive in the order expected. Therefore by using unseenOnly: true and a collection or matchOptions the waitForMatchingX endpoints lets you wait for specific emails in an asynchronous way.

Motivation for match and wait methods

Wait and match methods differ from fetching existing emails in that they poll a database until expected matches are found. The getEmails methods on the email controller only return existing emails so using them can result in unexpected results if an email has not yet arrived.

What does waiting for emails mean?

Wait methods with MailSlurp retry a query against the database until an expected result count is found or a timeout is reached. If a timeout is reached and the expected results were not found a 404 error exception is returned.

Let’s take a look at some waiting examples using the Javascript SDK.

Common wait method

MailSlurp provides many wait methods. See the WaitForController for all wait methods.

waitForLatestEmail

Wait for the latest email in the inbox. Latest is the email with the received time closest to the present. Note if the inbox is not empty the method will return the most recent email immediately and not wait. Pass unreadOnly=true to ensure the method waits for a new unseen email. Once the email is returned it will be marked as read.

const timeoutMillis = 60000;
const unreadOnly = true;
const email = await waitForController.waitForLatestEmail({
  inboxId: inbox.id!,
  timeout: timeoutMillis,
  unreadOnly: unreadOnly,
});

waitForEmailCount

Wait for given number of emails to be present in the given inbox. Pass unreadOnly=true to ensure that the emails are new emails and the method waits. Otherwise, if the inbox already contains the number given it will return immediately.

// wait for 2 emails
const emails = await waitForController.waitForEmailCount({
  count: 2,
  inboxId: inbox.id!,
  timeout: timeoutMillis,
  unreadOnly: false,
  sort: WaitForEmailCountSortEnum.ASC,
});
expect(emails.length).toEqual(2);

waitForNthEmail

If nth email is already present in inbox then return it. If not hold the connection open until timeout expires or the nth email is received and returned. Uses a zero based index of the email to wait for. If an inbox has 1 email already and you want to wait for the 2nd email pass index=1.

const nthEmail = await waitForController.waitForNthEmail({
  inboxId: inbox.id!!,
  timeout: timeoutMillis,
  index: 1,
});

If you want to see more email and inbox operations see the fetching email content guide or the matching options below.

Match options

Matching allows you to wait for specific emails that have a particular attachment count, subject line, recipient etc. Email match operations typically apply a list of patterns to fields of emails (excluding the body) to return a set of matching results.

The basic definitions are defined like so:

export enum MatchOptionFieldEnum {
    SUBJECT = 'SUBJECT',
    TO = 'TO',
    BCC = 'BCC',
    CC = 'CC',
    FROM = 'FROM'
}

export enum MatchOptionShouldEnum {
    CONTAIN = 'CONTAIN',
    EQUAL = 'EQUAL'
}

Match usage example

Construct match options with multiple matches. They will be sequentially applied as filters to the emails found in an inbox. The operation will continue until the desired number of matching emails is found.

// filter for emails containing the subject "Apples". 
 const matchOptions = {
    matches: [
        {
            field: "SUBJECT",
            should: "CONTAIN",
            value: "Apples"
        }
    ]
};

Then using the Javascript SDK you can wait for expected matching emails.

const mailslurp = new MailSlurp({ apiKey: process.env.API_KEY! });
const inbox = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();
const timeoutMillis = 30000;
await mailslurp.sendEmail(inbox2.id!, {
  to: [inbox.emailAddress!],
  subject: 'Apples',
});

const matchingEmails = await mailslurp.waitController.waitForMatchingEmails(
  {
    matchOptions: {
      matches: [
        {
          field: MatchOptionFieldEnum.FROM,
          should: MatchOptionShouldEnum.CONTAIN,
          value: inbox2.emailAddress,
        },
      ],
    },
    count: 1,
    inboxId: inbox.id,
    timeout: timeoutMillis,
    unreadOnly: true,
  }
);

// expect the apples email to have been matched due to the subject condition
expect(matchingEmails.length).toEqual(1);
expect(matchingEmails[0].subject).toEqual('Apples');

waitForMatchingFirstEmail

Wait for the first email matching the given match options.

const singleMatch =
  await mailslurp.waitController.waitForMatchingFirstEmail({
    inboxId: inbox.id!,
    timeout: timeoutMillis,
    unreadOnly: true,
    matchOptions: {
      conditions: [
        {
          condition: ConditionOptionConditionEnum.HAS_ATTACHMENTS,
          value: ConditionOptionValueEnum.FALSE,
        },
      ],
      matches: [
        {
          field: MatchOptionFieldEnum.FROM,
          should: MatchOptionShouldEnum.CONTAIN,
          value: inbox2.emailAddress,
        },
      ],
    },
  });
expect(singleMatch.subject).toContain('Apples');

Next steps