Axios is a popular HTTP request library for JavaScript and Node.js. It lets you call APIs from browser and server environments with simple request patterns.

With a MailSlurp account, Axios can power full email workflows: create inboxes, send messages, and validate received content in tests.

Executive summary

  • Use Axios to call MailSlurp inbox and email endpoints.
  • Create temporary inboxes per run to isolate tests.
  • Send messages via API and assert subject/body on receipt.
  • Reuse the same flow for CI and local automation.

What is Axios?

You can install Axios from NPM as follows:

npm install axios

Making a request is easy once installed:

const axios = require("axios");
axios
  .get("/user?ID=12345")
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

What is MailSlurp?

MailSlurp is an email API for testing and automation. You can create email addresses on demand, then send and receive emails from JavaScript. You can create a free account then use the API key to send and receive emails with Axios.

How to use email with Axios

To use MailSlurp with Axios, first import the library and your API key.

const axios = require("axios");
const API_KEY = "your-mailslurp-api-key";

Create an inbox

First we can create an email address like so:

async function createInbox() {
  // call MailSlurp createInbox endpoint
  return await axios
    .post(`https://api.mailslurp.com/createInbox?apiKey=${API_KEY}`)
    .then((res) => res.data);
}

MailSlurp inboxes have real email addresses that can send and receive email.

{
  "id": "123",
  "emailAddress": "123@mailslurp.com"
}

Send an email

Sending email with Axios is straightforward using MailSlurp's send endpoint. POST data to https://api.mailslurp.com/sendEmail. Include your API key as a query parameter: ?apiKey=your-api-key.

// send email from inbox 1 to inbox 2
// NOTE you can send emails to any address with MailSlurp
await axios({
  method: "POST",
  url: `https://api.mailslurp.com/sendEmail?apiKey=${API_KEY}`,
  data: {
    senderId: inbox1.id,
    to: inbox2.emailAddress,
    subject: "Hello inbox 2",
    body: "Test from inbox 1",
  },
});

Receive emails

You can receive emails with MailSlurp too:

// receive the email from inbox 2
const email = await axios
  .get(`https://api.mailslurp.com/waitForLatestEmail?apiKey=${API_KEY}&inboxId=${inbox2.id}`)
  .then((res) => res.data);
expect(email.from).toEqual(inbox1.emailAddress);
expect(email.subject).toEqual("Hello inbox 2");
expect(email.body).toEqual("Test from inbox 1");

Next steps

You can use Axios and MailSlurp for sending, receiving, and end-to-end email testing.

Axios production checklist

Before shipping Axios-based email flows: