MailSlurp logo

blog

Send and receive email with the MailSlurp GraphQL API

Use MailSlurp's GraphQL email API to create inboxes, send messages, receive email, and explore queries and mutations in the browser playground.

Send and receive email with the MailSlurp GraphQL API article preview

GraphQL lets a client ask for the fields it needs through a typed schema. MailSlurp exposes an email API through GraphQL so you can create inboxes, read messages, and send email without switching endpoints for every operation. The browser explorer is especially useful when you are learning the schema because it keeps the documentation beside the query you are writing.

Where is it?

Open the MailSlurp GraphQL email API to use the browser explorer, or connect your own GraphQL client. See the inbox guide for the MailSlurp resources used in queries.

Install GraphQL client

You can install MailSlurp's GraphQL library using npm:

// uses the native fetch API built into Node.js
import { getLogger } from "../lib/logger";

You will need a MailSlurp API key. Create one in the MailSlurp account dashboard, store it safely, and configure the client to send it in the x-api-key header.

// create a helper that sends GraphQL POST requests to the MailSlurp endpoint
// and passes your MailSlurp API key in the x-api-key header

Making a query

The example gql call uses a JavaScript template literal. A raw query string works too if that fits your client better.

const query = `
  {
    inboxes {
      numberOfElements
    }
  }
`;
const { inboxes } = await graphqlRequest<{
  inboxes: { numberOfElements: number };
}>(query);
expect(inboxes.numberOfElements).toBeGreaterThan(0);

You can explore the complete schema in the MailSlurp GraphQL Playground.

Mutations

Here is how you can perform mutations.

const { createInbox } = await graphqlRequest<{
  createInbox: { id: string; emailAddress: string };
}>(`
  mutation {
    createInbox {
      id
      emailAddress
    }
  }
`);
expect(createInbox.id).toBeTruthy();
expect(createInbox.emailAddress).toContain("@");

Send email

And here is a way to send emails using GraphQL.

const { sendEmail } = await graphqlRequest<{
  sendEmail: { id: string };
}>(
  `
    mutation SendEmail(
      $fromInboxId: String!
      $to: [String!]!
      $subject: String!
    ) {
      sendEmail(fromInboxId: $fromInboxId, to: $to, subject: $subject) {
        id
      }
    }
  `,
  {
    fromInboxId: createInbox.id,
    to: [createInbox.emailAddress],
    subject: "Test",
  },
);
expect(sendEmail.id).toBeDefined();

Further reading

For more information please see the GraphQL email guide.