7

GraphQL Email API Tutorial

 2 years ago
source link: https://www.mailslurp.com/blog/graphql-email-api-tutorial/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
GraphQL Email API Tutorial

GraphQL Email API Tutorial

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:

// npm install --save graphql-request
import { gql, GraphQLClient } from 'graphql-request';

Note you will need a free MailSlurp API key. Create an API key at https://app.mailslurp.com/sign-up/ 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 new graphql-request client using the MailSlurp graphql endpoint
// and passing a headers map including your MailSlurp API Key using "x-api-key" header
const client = new GraphQLClient('https://graphql.mailslurp.com', {
  headers: {
    'x-api-key': YOUR_API_KEY,
  },
});

Making a query

You can make queries like so. Note that the example gql method call should use backticks ` to use template string invocation. They are shown below as double quotes " because of formatting issues. Note you can use raw strings without gql too if you prefer.

const query = gql"
  {
    inboxes {
      totalElements
    }
  }
";
const { inboxes } = await client.request(query);
expect(inboxes.totalElements).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 client.request(gql"
  mutation {
    createInbox {
      id
      emailAddress
    }
  }
");
expect(createInbox.id).toBeTruthy();
expect(createInbox.emailAddress).toContain('@mailslurp');

Send email

And here is a way to send emails using GraphQL.

const { sendEmail } = await client.request(gql"
  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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK