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

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

// return emails currently in an inbox
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.

const email = await mailslurp.getEmail(email.id);
console.log(email);
// { id: '', body: '',  attachments: [] }

The full email content is available on the body property.

WARNING

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

# 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 inboxController.createInbox({})
    await inboxController.sendEmailAndConfirm({
        inboxId: inbox1.id,
        sendEmailOptions: {
            to: [inbox1.emailAddress],
            body: `Dear user,\n\nHere is a multiline email.\nThanks`,
        }
    });
    const email = await waitController.waitForLatestEmail({
        inboxId: inbox1.id,
        timeout: 60000,
        unreadOnly: true
    });
    const linesResult = await 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 () => {
    jest.setTimeout(60000)
    const inbox1 = await inboxController.createInbox({})
    await 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 waitController.waitForLatestEmail({
      inboxId: inbox1.id,
      timeout: 60000,
      unreadOnly: true
    });
    const htmlResult = await 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"]
    });
});

TIP

For more email body methods see the email content 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.

# 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.waitFor({
  inbox: inbox.id,
  count: 1,
  timeout: 30000,
  unreadOnly: true,
});

TIP

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 atleast 4 emails in an inbox
const emails = await mailslurp.waitForEmailCount(
  4,
  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.

# 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({
  inboxId,
  count,
  matchOptions: [
    {
      field: "SUBJECT",
      should: "CONTAIN",
      value: "Welcome!",
    },
  ],
});

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

TIP

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.

const waitForController = new WaitForControllerApi(config);
const confirmation = await waitForController.waitForMatchingFirstEmail({
  inboxId,
  unreadOnly: true,
  timeout: 30000,
  matchOptions: {
    matches: [
      {
        field: MatchOptionFieldEnum.SUBJECT,
        should: MatchOptionShouldEnum.CONTAIN,
        value: "Please click the link provided"
      }
    ]
  }
});
const results = /<p>(https.+)<\/p>/g.exec(confirmation.body!!) || [];
expect(results.length).toBe(2);
const url = decodeURIComponent(results[1]);

# Using webhooks

Another way to receive emails is by using Webhooks.

TIP

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.

# 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 (opens new window)

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

# Email contents

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

Next page