Skip to content

Use inbound TXT/SMS

MailSlurp supports creation and management of real mobile phone numbers in multiple regions. Phone numbers can receive inbound SMS text messages that can be read and received in code, tests, or online.

sms-basic

Common use for SMS includes testing OTP codes. See the tutorials for examples: - Playwright SMS testing - Cypress SMS testing

Creating phone numbers

First add a phone plan to your account subscription. Then provision a phone number for the plan in the MailSlurp dashboard. Phone numbers have an ID and a number. When fetching the phone number use the ID.

Create phone

Viewing numbers

Use the PhoneControllerApi to manage phone numbers.

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')

List and view SMS messages

Use the SmsControllerApi to view and download SMS messages.

const result = await mailslurp.smsController.getSmsMessagesPaginated({
    phoneNumber: phoneNumber.id
});
expect(result.totalElements).toBeGreaterThan(0);
// content contains array of sms messages
expect(result.content[0].body).toContain('Your code')

You can fetch individual messages using the message's ID.

// fetch a message
const txtMessage = await mailslurp.smsController.getSmsMessage({
    smsId: sms.id // UUID of the SMS message
})
expect(txtMessage.read).toEqual(true)
expect(txtMessage.fromNumber).toEqual('+13252527014')

Send a test message

You can instruct MailSlurp to send a test message to your phone number using the test messages:

await mailslurp.phoneController.testPhoneNumberSendSms({
    phoneNumberId: phoneNumber.id,
    xTestId: testId,
    testPhoneNumberOptions: {
        message: 'Your code: 123'
    },
});

Wait for new SMS messages

Use the WaitForControllerApi waitForSms methods to hold a connection open until an expected count of SMS messages is present in a phone number

// 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')

Use SMS webhooks

Have SMS messages sent via HTTP POST to your server with TXT Webhooks

// 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',
    }
})