Quick Start Javascript

Starting sending and receiving emails in no time with MailSlurp's official NodeJS Client.

Introduction

MailSlurp is a free API for sending and receiving emails from applications or tests. It is designed as a simpler, more powerful interface for SMTP mail servers. You can use MailSlurp for any email related process including testing and normal sending and receiving.

Questions

For any questions or issues please reach out any time using live chat or email.

API Key

All MailSlurp requests require an API Key. Get your API Key by signing up.

Install

MailSlurp can be used a REST API or with officially supported clients in Javascript, Ruby, Python, PHP, Java, C#, Go and more.

This guide will use examples from the recommended Javascript client. For other languages and libraries please see the integrations page.

NPM Package

npm install --save mailslurp-client

Configuration

const { MailSlurp } = require('mailslurp-client');
const mailslurp = new MailSlurp({ apiKey: 'xxxxxx' })

Note: All requests require an API Key. Get yours free via the MailSlurp Dashboard

Create email addresses

MailSlurp uses the concept of an inbox. Inboxes have IDs and email addresses. If you want to receive emails you’ll need to create an inbox first.

const { id, emailAddress } = await mailslurp.createInbox()

createInbox() returns a randomly assigned email address such as 1234-5678@mailslurp.com. This address is unique, private, and only accessible by you. To use a specific address and domain see the custom domains guide.

What is an inbox?

An inbox has an id and a unique emailAddress. Free inboxes end in @mailslurp.com.

Any emails sent to an inbox’s email address will be routed to the inbox. All emails are stored privately.

Custom domains

You can register any domain that you have control of. See the custom domains guide for more.

Send emails

You can send real emails with MailSlurp. Attachments, templating, and forwarding are all possible.

Minimal example

The most simple send action requires an inbox and an array of at least one valid recipient email addresses.

mailslurp.sendEmail(inbox.id, { to: ['recipient@domain.com'] })

After executing the sendEmail method MailSlurp will send a real email to the recipient provided.

Email content

With MailSlurp you can send simple strings or HTML. Both methods support templating, attachments, and custom charsets.

mailslurp.sendEmail(inbox.id, { 
  to: ['recipient@domain.com'],
  isHTML: true,
  charset: 'utf-8',
  body: '<html>foo</html>',
})

Email templating

MailSlurp supports email templating using moustache syntax:

If you provide templateVariables in your send options MailSlurp will substitute any `` variables found in the subject or body.

For example:

mailslurp.sendEmail(inbox.id, { 
  to: ['recipient@domain.com'],
  subject: 'Welcome {{name.first}}',
  body: 'Your code is {{code}}'
  templateVariables: {
    code: 123,
    name: {
      first: 'Foo',
      last: 'Bar'
    }
  }
})

Attachments

To send attachments first upload each attachment you wish to send.

Attachment content should be a Base 64 encoded string.

const [id] = await mailslurp.uploadAttachment({
    base64Contents: 'base64-encoded-file-contents',
    contentType: "optional/content-type",
    filename: "optional-filename"
})

Once you have uploaded each attachment you can use the returned attachment IDs in the attachments field of the sendEmailOptions.

mailslurp.sendEmail(inbox.id, { 
  to: ['recipient@domain.com'],
  subject: 'Your document',
  attachments: [id]
})

Random test addresses

If you don’t care what address an email is sent from (perhaps for testing) use the sendEmailSimple method. This will send emails from a random MailSlurp address.

mailslurp.sendEmailSimple({ to: ['recipient@domain.com'], body: '', subject: '' })

More sending options

MailSlurp has many options for sending emails. Here are a few:

mailslurp.sendEmail(inbox.id, { 
  to: ['recipient@domain.com'],
  bcc: [],
  cc: [],
  from: '',
  headers: {},
  attachments: [],
  isHTML: false,
  charset: '',
  body: '',
  templateVariables: {}
})

For full details see the method documentation.

Receive emails

MailSlurp makes receiving emails easy. There is one important concept to understand:

Email is asynchronous by nature. That means many MailSlurp methods use a waitFor function and return once expected criteria have been met.

Simple receive

The easiest way to receive emails is to create a new empty inbox and send an email to it.

Then use waitForLatestEmail to hold a connection open until atleast one email appears in the inbox.

const {
  body,
  subject
} = await mailslurp.waitForLatestEmail(inbox.id)

Note: waitForLatestEmail will return immediately if the inbox contains an email.

Receiving with non-empty inboxes

If your inbox already contains some emails you can tell MailSlurp how many emails you expect it to contain.

You can get the number of emails in an inbox before you expect it to receive a new email address using the getEmails method.

// get current count
const { length }  = await mailslurp.getEmails(inbox.id)

// do something that sends and email to the inbox

// then get the new email
await mailslurp.waitForNthEmail(indox.id, length + 1, timeout)

Other methods

You can also wait for an inbox to contain an expected count and return all those emails:

const emails = await mailslurp.waitForEmailCount(count, inbox.id)

Note: MailSlurp will return immediately if the inbox already contains an email.

Advanced receiving

For more control over email fetching use the getEmails methods with extra parameters. MailSlurp will hang the connection until all conditions are met or the timeout is exceeded.

// get a list of matching emails in preview form
const emailPreviews = await mailslurp.getEmails(inbox.id, {
    minCount: 2, // wait until 2 emails present
    retryTimeout: 60000 // max milliseconds to wait
})
// then get the email you want in full form
const email = await mailslurp.getEmail(emailPreviews[0].id)

Receiving attachments

If an email contains an attachment MailSlurp will archive the file and make the file’s ID available in the email response. Something like so:

const { attachments } = await mailslurp.getEmail(email.id)
const httpResponse = await mailslurp.downloadAttachment(email.id, attachments.id)

Using Webhooks

Webhooks enable you to receive emails via push notifications to your server or app that contain an email ID.

Webhooks are scoped to individual inboxes and can be created like so:

await mailslurp.createWebhook(inbox.id, {
  name: 'optional',
  url: 'your http endpoint'
})

Searching emails

MailSlurp has simple but powerful email matching features that let you wait for an email that matches a particular subject, recipient or more.

const matchOptions = {
  matches: [
    {
      field: 'SUBJECT',
      should: 'CONTAIN',
      value: 'Welcome to my company'
    }
  ]
};
await mailslurp.waitForMatchingEmails(matchOptions, 1, inbox.id, 5000);

For more information on email matching see the documentation.

Deleting entities

You can empty an inbox easily with:

await mailslurp.emptyInbox(inbox.id)

Or delete it completely like so:

await mailslurp.deleteInbox(inbox.id)

You can also delete emails individually with:

await mailslurp.deleteEmail(email.id)

Full documentation

This guide covers only the most common MailSlurp features. For more details please see API/SDK documentation.

License

All MailSlurp libraries use an open MIT License.