blog
Here is a tutorial on how to use the GraphQL Email API.
Discover the Power of GraphQL with MailSlurp's Email API- Send and receive emails through GraphQL. Check out the free email address API endpoint now!
GraphQL is a hot new technology for fetching data using a graph. MailSlurp offers a free email address API that you can use to create inboxes, read email, send emails and more. Let's see how it works.
Where is it?
Access the MailSlurp GraphQL email API endpoint at https://graphql.mailslurp.com. If you load the url in a browser you'll see the GraphQL explorer. You can use it to perform queries or use your own graphql client locally.
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";
Note you will need a free MailSlurp API key. Create an API key at MailSlurp account dashboard and store the value safely. Then use the key in code to configure the client. We must create a client that sets an x-api-key header using your MailSlurp account API KEY.
// 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
You can make queries like so. Note that the example gql method call should use backticks ` to use template string invocation. Note you can use raw strings without gql too if you prefer.
const query = `
{
inboxes {
numberOfElements
}
}
`;
const { inboxes } = await graphqlRequest<{
inboxes: { numberOfElements: number };
}>(query);
expect(inboxes.numberOfElements).toBeGreaterThan(0);
The great thing about graphql is that you can explore the MailSlurp API schema yourself using the provided 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.