Receiving emails

Email is an asynchronous technology meaning email delivery times are inherently unpredictable. MailSlurp was built to solve this problem. Here are some examples of fetching emails using the Javascript SDK - the same methods are available in all languages.

Key concepts

Emails are received by inboxes and stored in the database. You can fetch existing emails from an inbox or you can use wait and match methods to wait for an expected number of emails to arrive in an inbox that match given conditions such as subject line, recipients etc. In addition one can also use webhooks to recieve emails via HTTP POST to your server.

receive emails

Emails are marked as unread when they are received and marked as read when they are opened in the dashboard or requested directly by the API. To override this behaviour see the set email seen guide.

If you are having issues receiving emails please see the inbox not receiving support page.

Email receiving options

To recap there are 3 main ways to receive emails with MailSlurp:

  • Fetch existing emails from inboxes in list form or directly using a known email ID
  • Wait for matching emails to arrive (by automatically recalling the server until a condition is met)
  • Receive emails and attachments directly to your server via webhooks

All three methods can be managed in the MailSlurp dashboard, REST API, or using an SDK client. Let us cover these methods now.

Fetching existing emails

If you are not expecting new emails you can fetch the existing emails in an inbox directly using the inbox’s ID and the EmailControllerAPI methods. If you are expecting an email to arrive use the wait for methods or an email webhook.

// return emails currently in an inbox (limited to 100 entities, use pagination for larger responses)
const emails = await mailslurp.getEmails(inbox.id!!);

Email responses contain a preview of an email.

console.log(emails);
// [ { id: '', to: [], subject: '', ...etc } ]

To receive the full email use the email ID with the getEmail method.

_log
  console.log(emails);
  // [ { id: '', to: [], subject: '', ...etc } ]
  

The full email content is available on the body property.

MailSlurp recommends using waitFor methods over getEmails as the emails you expect may not have arrived when you call MailSlurp. waitFor solves this problem. See the WaitForControllerApi for documentation.

Viewing emails visually

You can view emails and attachments online using the dashboard or in code.

View email

Query email content

Given a known email ID you can fetch the email content in various others ways.

Fetch body

Fetch the raw body using the getEmail method.

const { body } = await mailslurp.getEmail(email.id!!);

Get lines of text in email

If you wish to parse the email content and return an array of text use the following methods:

// example using mailslurp-client for Node and Jest
it('can extract text lines', async () => {
  jest.setTimeout(60000);
  const inbox1 = await mailslurp.inboxController.createInbox({});
  await mailslurp.inboxController.sendEmailAndConfirm({
    inboxId: inbox1.id!!,
    sendEmailOptions: {
      to: [inbox1.emailAddress!!],
      body: 'Dear user,\n\nHere is a multiline email.\nThanks',
    },
  });
  const email = await mailslurp.waitController.waitForLatestEmail({
    inboxId: inbox1.id,
    timeout: 60000,
    unreadOnly: true,
  });
  const linesResult = await mailslurp.emailController.getEmailTextLines({
    emailId: email.id!!,
    decodeHtmlEntities: true,
  });
  expect(linesResult.lines).toEqual([
    'Dear user,',
    'Here is a multiline email.',
    'Thanks',
  ]);
});

Query email HTML content

You can also query HTML content using common CSS selectors.

it('can extract html and lines', async () => {
  const inbox1 = await mailslurp.inboxController.createInbox({});
  await mailslurp.inboxController.sendEmailAndConfirm({
    inboxId: inbox1.id!!,
    sendEmailOptions: {
      to: [inbox1.emailAddress!!],
      body: '<p>Hello <span class="name">Bob</span> you have mail</p>',
      isHTML: true,
    },
  });
  const email = await mailslurp.waitController.waitForLatestEmail({
    inboxId: inbox1.id,
    timeout: 60000,
    unreadOnly: true,
  });
  const htmlResult = await mailslurp.emailController.getEmailHTMLQuery({
    emailId: email.id!!,
    htmlSelector: '.name',
  });
  expect(htmlResult).toEqual({
    body: '<p>Hello <span class="name">Bob</span> you have mail</p>',
    // the matches for .name selector
    lines: ['Bob'],
  });
});
For more email body methods see the email content guide or the wait for matching emails guide

Waiting for emails

What about emails that may not have arrived yet? MailSlurp waitFor methods allow you to wait for emails to arrive in an inbox. The WaitForControllerApi contains many methods to receive incoming emails.

It is important to set a timeout when waiting for emails. Email is a slow protocol and provider may differ in their sending speeds. We recommend a timeout of at least 60000ms.

Basic

The standard waitFor method takes an inboxId, expected count and a timeout. When called MailSlurp will check the inbox for emails. If the count equals or exceeds the given count the emails will be returned immediately.

If not MailSlurp will wait until the expected emails to arrive and the count is met before returning. If the timeout is exceeded an error will be thrown. You can also pass an unreadOnly parameter so that only unread email are counted.

// return at least one unread email or wait 30 seconds for one to arrive
const [email] = await mailslurp.waitController.waitFor({
  waitForConditions: {
    inboxId: inbox.id!,
    count: 1,
    timeout: 30000,
    unreadOnly: true,
  },
});
WaitFor methods will return immediately if the conditions passed are already met by an inbox. If not MailSlurp will retry the conditions until a timeout has been reached. You must ensure your application or test HTTP timeout allows for this.

Advanced

There are several other waitFor methods that each have different use-cases.

// Wait for an email to arrive at an inbox or return first found result
const email = await mailslurp.waitForLatestEmail(
  inboxId,
  timeout,
  unreadOnly
);

// Return or wait for email number 'n' in an inbox (0 based index)
const secondEmail = await mailslurp.waitForNthEmail(
  inboxId!!,
  1,
  timeout,
  unreadOnly
);

// Return or wait for at least 2 emails in an inbox
const emails = await mailslurp.waitForEmailCount(
  2,
  inboxId,
  timeout,
  unreadOnly
);

For full method documentation see the docs page.

Matching and searching emails

MailSlurp also lets you wait for emails based on search pattern matching on fields within an email. See the WaitForControllerApi methods for more information.

Wait for matching

For instance, you could wait for a welcome email during an integration test of your sign-up process by matching the subject line.

const [welcomeEmail] = await mailslurp.waitForMatchingEmails(
  {
    conditions: [
      {
        condition: ConditionOptionConditionEnum.HAS_ATTACHMENTS,
        value: ConditionOptionValueEnum.FALSE,
      },
    ],
    matches: [
      {
        field: MatchOptionFieldEnum.SUBJECT,
        should: MatchOptionShouldEnum.CONTAIN,
        value: 'Welcome!',
      },
    ],
  },
  expectedCount,
  inboxId
);

Here is an example of using a match to extract a verification:

See email matching guide for more usage.

Imagine a test where you have created an inbox and signed up for your application using it. Then we can use a match for first email that contains the expected subject. Finally we using a regex we can extract the url. See the extracting email content guide for more examples.


// send an email containing a link to the inbox
await mailslurp.sendEmail(inboxId!, {
  to: [emailAddress!],
  subject: 'Please click the link provided',
  body: '<p>https://my.app/confirm</p>',
});
// wait for matching email to arrive with desired subject
const waitForController = new WaitForControllerApi(
  new Configuration({ apiKey })
);
const confirmation = await waitForController.waitForMatchingFirstEmail({
  inboxId,
  unreadOnly: true,
  timeout: 30000,
  matchOptions: {
    matches: [
      {
        field: MatchOptionFieldEnum.SUBJECT,
        should: MatchOptionShouldEnum.CONTAIN,
        value: 'Please click the link provided',
      },
    ],
  },
});
// extract the link using regex pattern on the confirmation body
const results = /<p>(https.+)<\/p>/g.exec(confirmation.body!)!;
expect(results.length).toBe(2);
const url = decodeURIComponent(results[1]);
expect(url).toContain('https://my.app/confirm');

Using webhooks

Another way to receive emails is by using Webhooks.

If you are receiving high numbers of emails we highly recommend webhooks. They are backed by message queues and route emails directly to an HTTP endpoint on your server in real-time.

Please see the using webhooks guide or the developer webhook documentation for more information.

Requirements

To use a Webhook you must have a publicly accessible URL endpoint that can receive HTTP POST JSON payloads (such as an API or server).

Creating webhooks

You can create webhooks in the MailSlurp dashboard or programmatically. Webhooks are associated with a single inbox.

await mailslurp.createWebhook(inboxId, {
  url: "http://yourapi.com/inbound-emails",
});

Webhook payloads

Each time an inbox receives an email MailSlurp will check for any associated webhooks and send a JSON payload to the URL. The payload contains information about the email and is described by the webhook payload schema

{
  "inboxId": "",
  "eventName": "EMAIL_RECEIVED",
  ...etc
}

For more information on webhooks see the Webhook guide or the webhook API endpoints.

Email contents

Now that email receiving is covered let’s see what the emails themselves look like in the next section.

Next page