Receive inbound SMS TXT messages with API and webhooks

  • Table of contents

How to create phone numbers and read text messages in code and tests. Receive inbound SMS in via webhook or fetch.

Process SMS (TXT) messages in code, tests, and online dashboards using MailSlurp's Phone and SMS APIs. This post will cover the main features and show you how to get started.

Overview

MailSlurp's phone and SMS APIs allow you to create phone numbers in real locations and receive inbound SMS/TXT messages.

Manage phone numbers

You can fetch and list phone numbers using the phone number controller in any client or using the REST API. Below is an example using the official Javascript library.

const mailslurp = new MailSlurp({ apiKey });
// fetch a phone number (must create phone numbers in the dashboard first)
const {
  content: [phoneNumber],
} = await mailslurp.phoneController.getPhoneNumbers({
  size: 1,
  phoneCountry: GetPhoneNumbersPhoneCountryEnum.US,
});
expect(phoneNumber.phoneNumber).toEqual('+19108074451');

Read SMS messages

Use get methods to fetch SMS messages or use the waitFor and webhook options if you need to allow for time for the message to be received after performing some SMS-sending action in your system.

// fetch a message
const txtMessage = await mailslurp.smsController.getSmsMessage({
  smsId: sms.id,
});
expect(txtMessage.read).toEqual(true);
expect(txtMessage.fromNumber).toEqual('+13252527014');
// delete all messages in phone number
await mailslurp.smsController.deleteSmsMessages({
  phoneNumberId: sms.phoneNumber,
});

Wait for expected TXT message

Use the WaitController to hold a connection until an SMS condition is met. Here we can see how to wait for the latest unread SMS to be received in a phone number. Waiting for SMS with a method allows you to test asynchronous SMS features in your application. See the SMS usage guide to get started.

// wait for the latest unread sms
const [sms] = await mailslurp.waitController.waitForSms({
  waitForSmsConditions: {
    count: 1,
    unreadOnly: true,
    phoneNumberId: phoneNumber.id,
    timeout: 30_000,
  },
});
// extract a code from body with regex
expect(sms.body).toContain('Your code: 123');
const [, code] = /.+:\s([0-9]{3})/.exec(sms.body);
expect(code).toEqual('123');

New SMS event webhooks

Create a webhook for a phone number if you want to have new inbound SMS sent directly to your own system server endpoint.

// create a webhook for a phone number to have new SMS sent to your server
const webhook =
  await mailslurp.webhookController.createWebhookForPhoneNumber({
    phoneNumberId: phoneNumber.id,
    createWebhookOptions: {
      eventName: CreateWebhookOptionsEventNameEnum.NEW_SMS,
      url: 'https://myserver.com',
      name: 'Process SMS',
    },
  });

For more information see the webhook documentation.

Sending SMS

MailSlurp does not currently support outbound SMS messaging. If you require this please contact support.