Sending High Volume SMS

Last updated: 2024-01-31Contributors
Edit this page

The High Volume SMS API provides a very flexible way to send multiple SMS message in a single API request (a.k.a. a batch). In other words, one can send the same text message to different recipients and/or different text messages to different recipients in a single request.

There is no limit of number of recipients in a batch. However, the maximum size of each batch is about 50MB.

Sample codes

Simple request to broadcast the same message to multiple recipients.

Running the code

  • If you have tried the SMS quick start, you can just copy all the functions below and add them to the quick start project then call the read_extension_phone_number_detect_a2psms_feature() function. Otherwise, edit the variables in ALL CAPS with your app and user credentials before running the code.
  • High volume SMS is not supported on sandbox environment. If you copy/paste the functions below and call them in the quick start project, remember to change the environment to use your app and user credentials for production!
POST /restapi/v1.0/account/~/a2p-sms/batches
Content-Type: application/json
Accept: application/json

{
  "from": "+16505550100",
  "text": "Hello Team",
  "messages": [
    { "to": ["+14155550100"] },
    { "to": ["+12125550100"] }
  ]
}
const RC = require('@ringcentral/sdk').SDK

// Instantiate the SDK and get the platform instance
var rcsdk = new RC({
    server: "https://platform.ringcentral.com",
    clientId: "PRODUCTION-APP-CLIENTID",
    clientSecret: "PRODUCTION-APP-CLIENTSECRET"
});
var platform = rcsdk.platform();

/* Authenticate a user using a personal JWT token */
platform.login({ jwt: "PRODUCTION-JWT" })

// For the purpose of testing the code, we put the recipient number in the variable.
// Feel free to set the recipient number directly.
var RECIPIENT = "RECIPIENT-PHONE-NUMBER"

platform.on(platform.events.loginSuccess, function(e){
    read_extension_phone_number_detect_a2psms_feature()
});

platform.on(platform.events.loginError, function(e){
    console.log("Unable to authenticate to platform. Check credentials.", e.message)
    process.exit(1)
});

/*
  Read phone number(s) that belongs to the authenticated user and detect if a phone number
  has the A2P SMS capability
*/
async function read_extension_phone_number_detect_a2psms_feature(){
  try {
      let endpoint = "/restapi/v1.0/account/~/extension/~/phone-number"
      var resp = await platform.get(endpoint)
      var jsonObj = await resp.json()
      for (var record of jsonObj.records){
          for (feature of record.features){
              if (feature == "A2PSmsSender"){
                // If a user has multiple phone numbers, check and decide which number
                // to be used for sending text message.
                return await send_batch_sms(record.phoneNumber)
              }
          }
      }
      if (jsonObj.records.length == 0)
        console.log("This user does not own a phone number!")
      else
        console.log("None of this user's phone number(s) has A2P SMS capability!")
  } catch(e) {
      console.log(e.message)
  }
}

/*
 Broadcast a text message from a user own phone number to multiple recipients
*/
async function send_batch_sms(fromNumber) {
    try{
        let bodyParams = {
            from: fromNumber,
            text: "Hello Team",
            messages: [
                { to: [RECIPIENT] },
              // Adding more recipients
              /*
              { to: [ "Recipient-2-Phone-Number" ] },
              { to: [ "Recipient-N-Phone-Number" ] }
              */
            ]
        }
        let endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
        var resp = await platform.post(endpoint, bodyParams)
        var jsonObj = await resp.json()
        console.log("Batch sent. Batch id: " + jsonObj.id)
        check_batch_status(jsonObj.id)
    }catch(e){
        console.log(e.message)
    }
}

/*
 Send a batch from a user own phone number to multiple recipient with personalized message
*/
async function send_personalized_sms(fromNumber) {
    try{
        let bodyParams = {
            from: fromNumber,
            // This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
            text: "Hello Team",
            messages: [
                { to: [RECIPIENT], text: "Hello Alice" },
              // Adding more recipients
              /*
              { to: [ "Recipient-2-Phone-Number" ], text: "Hello Bob" },
              { to: [ "Recipient-N-Phone-Number" ], text: "Hola Maria" }
              */
            ]
        }
        let endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
        var resp = await platform.post(endpoint, bodyParams)
        var jsonObj = await resp.json()
        console.log("Batch sent. Batch id: " + jsonObj.id)
        check_batch_status(jsonObj.id)
    }catch(e){
        console.log(e.message)
    }
}

/*
 Check the batch status until it's completed.
 Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
*/
async function check_batch_status(batchId){
  try {
      let endpoint = `/restapi/v1.0/account/~/a2p-sms/batches/${batchId}`
      let resp = await platform.get(endpoint);
      let jsonObj = await resp.json()
      console.log("Batch status: ", jsonObj.status)
      if (jsonObj.status != "Completed"){
        await sleep (5000);
        check_batch_status(jsonObj.id);
      }else{
        console.log(jsonObj)
      }
  } catch (e) {
    console.log(e.message)
  }
}

const sleep = async (ms) => {
  await new Promise(r => setTimeout(r, ms));
}
import time, json
from ringcentral import SDK

# Read phone number(s) that belongs to the authenticated user and detect if a phone number
# has the A2P SMS capability
def read_extension_phone_number_detect_a2psms_feature():
    try:
        endpoint = "/restapi/v1.0/account/~/extension/~/phone-number"
        resp = platform.get(endpoint)
        jsonObj = resp.json()
        for record in jsonObj.records:
            for feature in record.features:
                if feature == "A2PSmsSender":
                    # If a user has multiple phone numbers, check and decide which number
                    # to be used for sending A2P SMS message.
                    return send_batch_sms(record.phoneNumber)

        if jsonObj.records.count == 0:
            print ("This user does not own a phone number!")
        else:
            print ("None of this user's phone number(s) has the A2P SMS capability!")
    except Exception as e:
        print (e)

#
# Broadcast a text message from a user own phone number to multiple recipients
#
def send_batch_sms(fromNumber):
    try:
        bodyParams = {
            'from': fromNumber,
            'text': "Hello Team",
            'messages': [
                { 'to': [RECIPIENT] }
            # Adding more recipients
            #   { 'to': [ "Recipient-2-Phone-Number"] },
            #   { 'to': [ "Recipient-N-Phone-Number"] }
            #
            ]
        }
        endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
        resp = platform.post(endpoint, bodyParams)
        jsonObj = resp.json()
        print ("Batch sent. Batch id: " + jsonObj.id)
        check_batch_status(jsonObj.id)
    except Exception as e:
        print (e)

#
# Send a batch from a user own phone number to multiple recipient with personalized message
#
def send_personalized_sms(fromNumber):
    try:
        bodyParams = {
            'from': fromNumber,
            # This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
            'text': "Hello Team",
            'messages': [
                { 'to': [RECIPIENT], 'text': "Hello Alice" }
            # Adding more recipients
            #   { 'to': [ "Recipient-2-Phone-Number"], 'text': "Hello Bob" },
            #   { 'to': [ "Recipient-N-Phone-Number"], 'text': "Hola Maria" }
            #
            ]
        }
        endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
        resp = platform.post(endpoint, bodyParams)
        jsonObj = resp.json()
        print ("Batch sent. Batch id: " + jsonObj.id)
        check_batch_status(jsonObj.id)
    except Exception as e:
        print (e)


#
# Check the batch status until it's completed.
# Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
#
def check_batch_status(batchId):
  try:
      endpoint =  "/restapi/v1.0/account/~/a2p-sms/batches/" + batchId
      resp = platform.get(endpoint)
      jsonObj = resp.json_dict()
      print ("Batch status: ", jsonObj['status'])
      if jsonObj['status'] != "Completed":
          time.sleep (5)
          check_batch_status(jsonObj['id'])
      else:
          print(json.dumps(jsonObj, indent=2, sort_keys=True))
  except Exception as e:
      print (e)

# Authenticate a user using a personal JWT token
def login():
    try:
      platform.login( jwt= "PRODUCTION_JWT" )
      read_extension_phone_number_detect_a2psms_feature()
    except Exception as e:
      print ("Unable to authenticate to platform. Check credentials." + str(e))

# Instantiate the SDK and get the platform instance
rcsdk = SDK("PRODUCTION-APP-CLIENTID", "PRODUCTION-APP-CLIENTSECRET", "https://platform.ringcentral.com")
platform = rcsdk.platform()

login()

# For the purpose of testing the code, we put the recipient number in the variable.
# Feel free to set the recipient number directly.
RECIPIENT = "RECIPIENT-PHONE-NUMBER"
####################################
<?php
require('vendor/autoload.php');

// Instantiate the SDK and get the platform instance
$rcsdk = new RingCentral\SDK\SDK( "PRODUCTION-APP-CLIENTID", "PRODUCTION-APP-CLIENTSECRET", "https://platform.ringcentral.com" );
$platform = $rcsdk->platform();

/* Authenticate a user using a personal JWT token */
try {
  $platform->login(["jwt" => "PRODUCTION-JWT"]);
}catch (\RingCentral\SDK\Http\ApiException $e) {
  // Getting error messages using PHP native interface
  print 'Expected HTTP Error: ' . $e;
  exit ("Error message: " . $e->apiResponse->response()->error() . PHP_EOL;
}

// For the purpose of testing the code, we put the recipient number in the variable.
// Feel free to set the recipient number directly.
$RECIPIENT = "RECIPIENT-PHONE-NUMBER";

read_extension_phone_number_detect_a2psms_feature();

/*
  Read phone number(s) that belongs to the authenticated user and detect if a phone number
  has the A2P SMS capability
*/
function read_extension_phone_number_detect_a2psms_feature(){
  global $platform;
  $endpoint = "/restapi/v1.0/account/~/extension/~/phone-number";
  $resp = $platform->get($endpoint);
  $jsonObj = $resp->json();
  foreach ($resp->json()->records as $record){
    if ($record->usageType == "DirectNumber"){
      foreach ($record->features as $feature){
        if ($feature == "A2PSmsSender"){
          // If a user has multiple phone numbers, check and decide which number
          // to be used for sending batch message.
          return send_batch_sms($record->phoneNumber);
        }
      }
    }
  }
  if (count($jsonObj->records) == 0)
    exit("This user does not own a phone number!");
  else
    exit("None of this user's phone number(s) has the A2P SMS capability!");
}

/*
 Broadcast a text message from a user own phone number to multiple recipients
*/
function send_batch_sms($fromNumber) {
  global $platform, $RECIPIENT;
  try {
    $bodyParams = array(
      'from' => $fromNumber,
      'text' => "Hello Team",
      'messages' => array(
        array ('to' => array ($RECIPIENT))
        // Adding more recipients
        /*
        array ('to' => array ("Recipient-2-Phone-Number")),
        array ('to' => array ("Recipient-N-Phone-Number"))
        */
    ));
    $endpoint = "/restapi/v1.0/account/~/a2p-sms/batches";
    $resp = $platform->post($endpoint, $bodyParams);
    check_batch_status($resp->json()->id);
  } catch (\RingCentral\SDK\Http\ApiException $e) {
    exit("Message: " . $e->message . PHP_EOL);
  }
}

/*
 Send a batch from a user own phone number to multiple recipient with personalized message
*/
function send_personalized_sms($fromNumber) {
  global $platform, $RECIPIENT;
  try {
    $bodyParams = array(
      'from' => $fromNumber,
      // This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
      'text' => "Hello Team",
      'messages' => array(
        array ('to' => array ($RECIPIENT), 'text' => "Hello Alice")
        // Adding more recipients
        /*
        array ('to' => array ("Recipient-2-Phone-Number"), 'text' => "Hello Bob"),
        array ('to' => array ("Recipient-N-Phone-Number"), 'text' => "Hola Maria")
        */
    ));
    $endpoint = "/restapi/v1.0/account/~/a2p-sms/batches";
    $resp = $platform->post($endpoint, $bodyParams);
    check_batch_status($resp->json()->id);
  } catch (\RingCentral\SDK\Http\ApiException $e) {
    exit("Message: " . $e->message . PHP_EOL);
  }
}

/*
 Check the batch status until it's completed.
 Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
*/
function check_batch_status($batchId) {
  global $platform;
  try {
      $endpoint = "/restapi/v1.0/account/~/a2p-sms/batches/".$batchId;
      $resp = $platform->get($endpoint);
      $jsonObj = $resp->json();
      print("Batch status: " . $jsonObj->status . PHP_EOL);
      if ($jsonObj->status != "Completed"){
        sleep(5);
        check_batch_status($jsonObj->id);
      }else{
        print_r (json_encode($jsonObj, JSON_PRETTY_PRINT) . PHP_EOL);
      }
  } catch (\RingCentral\SDK\Http\ApiException $e) {
    exit("Message: " . $e->message . PHP_EOL);
  }
}
?>
require 'ringcentral'

# Read phone number(s) that belongs to the authenticated user and detect if a phone number
# has the A2P SMS capability
def read_extension_phone_number_detect_a2psms_feature()
  begin
    endpoint = "/restapi/v1.0/account/~/extension/~/phone-number"
    resp = $platform.get(endpoint)
    for record in resp.body['records'] do
      for feature in record['features'] do
        if feature == "A2PSmsSender"
          # If a user has multiple phone numbers, check and decide which number
          # to be used for sending SMS message.
          return send_batch_sms(record['phoneNumber'])
        end
      end
    end
    if resp.body['records'].length == 0
      puts ("This user does not own a phone number!")
    else
      puts("None of this user's phone number(s) has the A2P SMS capability!")
    end
  rescue StandardError => e
    puts (e)
  end
end

#
# Broadcast a text message from a user own phone number to multiple recipients
#
def send_batch_sms(fromNumber)
  begin
    bodyParams = {
        'from': fromNumber,
        'text': "Hello Team",
        'messages': [
          { 'to': [RECIPIENT] }
        # Adding more recipients
        # { 'to': [ "Recipient-2-Phone-Number"] },
        #   { 'to': [ "Recipient-N-Phone-Number"] }
        #
        ]
    }

    endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
    resp = $platform.post(endpoint, payload: bodyParams)
    puts ("Batch sent. Batch id: " + resp.body['id'])
    check_batch_status(resp.body['id'])
  rescue StandardError => e
    puts (e)
  end
end

#
# Send a batch from a user own phone number to multiple recipient with personalized message
#
def send_personalized_sms(fromNumber)
  begin
    bodyParams = {
        'from': fromNumber,
        # This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
        'text': "Hello Team",
        'messages': [
          { 'to': [RECIPIENT], 'text': "Hello Alice" }
        # Adding more recipients
        # { 'to': [ "Recipient-2-Phone-Number"], 'text': "Hello Bob" },
        #   { 'to': [ "Recipient-N-Phone-Number"], 'text': "Hola Maria" }
        #
        ]
    }

    endpoint = "/restapi/v1.0/account/~/a2p-sms/batches"
    resp = $platform.post(endpoint, payload: bodyParams)
    puts ("Batch sent. Batch id: " + resp.body['id'])
    check_batch_status(resp.body['id'])
  rescue StandardError => e
    puts (e)
  end
end

#
# Check the batch status until it's completed.
# Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
#
def check_batch_status(batchId)
  begin
    endpoint =  "/restapi/v1.0/account/~/a2p-sms/batches/" + batchId
    resp = $platform.get(endpoint)
    puts ("Batch status: " + resp.body['status'])
    if (resp.body['status'] != "Completed")
        sleep (5)
        check_batch_status(resp.body['id'])
    else
        puts JSON.pretty_generate(JSON.parse(resp.body.to_json))
    end
  rescue StandardError => e
    puts (e)
  end
end

# Authenticate a user using a personal JWT token
def login()
  begin
    $platform.authorize( jwt: "PRODUCTION_JWT" )
    read_extension_phone_number_detect_a2psms_feature()
  rescue StandardError => e
    puts ("Unable to authenticate to platform. Check credentials." + e.to_s)
  end
end

# Instantiate the SDK and get the platform instance
$platform = RingCentral.new( "PRODUCTION-APP-CLIENTID", "PRODUCTION-APP-CLIENTSECRET", "https://platform.ringcentral.com" )

login()

# For the purpose of testing the code, we put the recipient number in the variable.
# Feel free to set the recipient number directly.
RECIPIENT = "RECIPIENT-PHONE-NUMBER"
####################################
using System;
using System.Threading.Tasks;
using RingCentral;

namespace Send_HighVolume_SMS
{
    class Program
    {
        // For the purpose of testing the code, we put the recipient number in the variable.
        // Feel free to set the recipient number directly.
        static string RECIPIENT = "RECIPIENT-PHONE-NUMBER";
        static RestClient restClient;

        static async Task Main(string[] args)
        {
          try
          {
            // Instantiate the SDK
            restClient = new RestClient( "PRODUCTION-APP-CLIENTID", "PRODUCTION-APP-CLIENTSECRET", "https://platform.ringcentral.com");

            // Authenticate a user using a personal JWT token
            await restClient.Authorize("PRODUCTION_JWT");
            await read_extension_phone_number_detect_a2psms_feature();
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
        /*
          Read phone number(s) that belongs to this user and detect if a phone number
          has the A2P SMS capability
        */
        static private async Task read_extension_phone_number_detect_a2psms_feature()
        {
            try
            {
                var resp = await restClient.Restapi().Account().Extension().PhoneNumber().Get();
                foreach (var record in resp.records)
                {
                    foreach (var feature in record.features)
                    {
                        if (feature == "A2PSmsSender")
                        {
                            // If a user has multiple phone numbers, check and decide which number
                            // to be used for sending SMS message.
                            await send_batch_sms(record.phoneNumber);
                            return;
                        }
                    }
                }
                if (resp.records.Length == 0)
                {
                    Console.WriteLine("This user does not own a phone number!");
                }
                else
                {
                    Console.WriteLine("None of this user's phone number(s) has the A2P SMS capability!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /*
         Broadcast a text message from a user own phone number to multiple recipients
        */
        static private async Task send_batch_sms(string fromNumber)
        {
            try
            {
                var bodyParams = new MessageBatchCreateRequest();
                bodyParams.from = fromNumber;
                bodyParams.messages = new MessageCreateRequest[] {
                    new MessageCreateRequest { to = new String[] { RECIPIENT } }
                    // Adding more recipients
                    /*
                    new MessageCreateRequest { to = new String[] { "Recipient2-Phone-Number } },
                    new MessageCreateRequest { to = new String[] { "RecipientN-Phone-Number } }
                    */
                };
                bodyParams.text = "Hello Team";

                var resp = await restClient.Restapi().Account().A2pSms().Batches().Post(bodyParams);
                Console.WriteLine("Batch sent. Batch id: " + resp.id);
                await check_batch_status(resp.id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /*
         Send a batch from a user own phone number to multiple recipient with personalized message
        */
        static private async Task send_personalized_sms(string fromNumber)
        {
            try
            {
                var bodyParams = new MessageBatchCreateRequest();
                bodyParams.from = fromNumber;
                bodyParams.messages = new MessageCreateRequest[] {
                    new MessageCreateRequest { to = new String[] { RECIPIENT }, text = "Hello Alice" }
                    // Adding more recipients
                    /*
                    new MessageCreateRequest { to = new String[] { "Recipient2-Phone-Number }, text = "Hello Bob" },
                    new MessageCreateRequest { to = new String[] { "RecipientN-Phone-Number }, text = "Hola Maria" }
                    */
                };
                // This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
                bodyParams.text = "Hello Team";

                var resp = await restClient.Restapi().Account().A2pSms().Batches().Post(bodyParams);
                Console.WriteLine("Batch sent. Batch id: " + resp.id);
                await check_batch_status(resp.id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /*
         Check the batch status until it's completed.
         Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
        */
        static private async Task check_batch_status(string batchId)
        {
            try
            {
                var resp = await restClient.Restapi().Account().A2pSms().Batches(batchId).Get();
                Console.WriteLine("Batch status: " + resp.status);
                if (resp.status != "Completed")
                {
                    Thread.Sleep(5000);
                    await check_batch_status(resp.id);
                }
                else
                {
                    Console.WriteLine(JsonConvert.SerializeObject(resp));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
package Send_HighVolume_SMS;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.ringcentral.*;
import com.ringcentral.definitions.*;

public class Send_HighVolume_SMS {
    // For the purpose of testing the code, we put the recipient number in the variable.
    // Feel free to set the recipient number directly.
    static String RECIPIENT = "RECIPIENT-PHONE-NUMBER";
    static RestClient restClient;

    public static void main(String[] args) {
      // Instantiate the SDK
      restClient = new RestClient( "PRODUCTION-APP-CLIENTID", "PRODUCTION-APP-CLIENTSECRET", "https://platform.ringcentral.com");
      var obj = new Send_HighVolume_SMS();
      try {
        // Authenticate a user using a personal JWT token
        restClient.authorize( "PRODUCTION_JWT" );
        obj.read_extension_phone_number_detect_a2psms_feature();
      } catch (RestException | IOException e) {
        e.printStackTrace();
      }
    }
    /*
    Read phone number(s) that belongs to the authenticated user and detect if a phone number
    has the A2P SMS capability
    */
    public void read_extension_phone_number_detect_a2psms_feature() throws IOException{
      try {
        var resp =  restClient.restapi().account().extension().phoneNumber().get();
        for (var record : resp.records) {
          if (record.usageType.equalsIgnoreCase("DirectNumber")) {
            for(var feature : record.features) {
              if (feature.equalsIgnoreCase("A2PSmsSender")) {
                // If a user has multiple phone numbers, check and decide which number
                // to be used for sending SMS message.
                send_batch_sms(record.phoneNumber);
                return;
              }
            }
          }
        }
        if (resp.records.length == 0) {
          System.out.println("This user does not own a phone number!");
        } else {
          System.out.println("None of this user's phone number(s) has the A2P SMS capability!");
        }
      }catch(RestException e) {
        System.out.println(e.getMessage());
      }
    }
    /*
     Broadcast a text message from a user own phone number to multiple recipients
    */
    public void send_batch_sms(String fromNumber) throws RestException, IOException{
      try {
        var bodyParams = new MessageBatchCreateRequest();
        bodyParams.from = fromNumber;
        bodyParams.text = "Hello Team";
        bodyParams.messages = new MessageCreateRequest[] {
          new MessageCreateRequest().to ( new String[] { RECIPIENT } ),
          // Adding more recipients
          /*
          new MessageCreateRequest().to ( new String[] { "Recipient-2-Phone-Number" } ),
          new MessageCreateRequest().to ( new String[] { "Recipient-N-Phone-Number" } ),
          */
        };

        var resp = restClient.restapi().account().a2pSms().batches().post(bodyParams);
        System.out.println("Batch sent. Batch id: " + resp.id);
        check_batch_status(resp.id);
      } catch(RestException e) {
        System.out.println(e.getMessage());
      }
    }
    /*
     Send a batch from a user own phone number to multiple recipient with personalized message
    */
    public void send_personalized_sms(String fromNumber) throws RestException, IOException{
      try {
        var bodyParams = new MessageBatchCreateRequest();
        bodyParams.from = fromNumber;
        bodyParams.messages = new MessageCreateRequest[] {
          new MessageCreateRequest().to ( new String[] { RECIPIENT } ).text ("Hello Alice") ,
            // Adding more recipients
            /*
              new MessageCreateRequest().to ( new String[] { "Recipient-2-Phone-Number" } ).text ("Hello Bob"),
              new MessageCreateRequest().to ( new String[] { "Recipient-N-Phone-Number" } ).text ("Hola Maria"),
            */
        };
        // This text becomes the default text and can be obmitted, if the text in a recipient object is not specified, this text will be used
        bodyParams.text = "Hello Team";

        var resp = restClient.restapi().account().a2pSms().batches().post(bodyParams);
        System.out.println("Batch sent. Batch id: " + resp.id);
        check_batch_status(resp.id);
      } catch(RestException e) {
        System.out.println(e.getMessage());
      }
    }
    /*
     Check the batch status until it's completed.
     Sending a large batch will take some time for the server to complete. You can read a batch status using the batch id returned in the response after sending a batch.
    */
    private void check_batch_status(String batchId) throws IOException {
      try {
        var resp = restClient.restapi().account().a2pSms().batches(batchId).get();
        System.out.println("Batch status: " + resp.status);
        if (!resp.status.equals("Completed")) {
          try {
            Thread.sleep(5000);
            check_batch_status(resp.id);
          } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(e);
          }
        }else{
          String jsonStr = new Gson().toJson(resp, new TypeToken<Object>(){}.getType());
          System.out.println(jsonStr);
        }
      } catch (RestException e) {
        System.out.println(e.getMessage());
      }
    }
}

Response

The code samples above would all produce a response that would appear similar to the one below.

{
    "id": "3157ac7d-baab-4d0e-1453-deada6c735d2",
    "from": "+16505550100",
    "batchSize": 1,
    "processedCount": 0,
    "status": "Processing",
    "creationTime": "2020-10-12T16:59:55.053902Z",
    "lastModifiedTime": "2020-10-12T16:59:55.053902Z",
    "rejected": []
}

Note

The rejected field is a list of invalid numbers (if any). Each item in the rejected array is an object contained the index position (starting from 1) of the recipient's phone number in the "messages" array, an error code and a short description of the rejected reason. E.g.:

[{"index":2,"to":["+4088070206"],"errorCode":"SMS-RC-410","description":"The recipient number is invalid"}]
If your batch contains invalid phone numbers, you will receive the rejected list with content only from the response returned by sending a batch. Reading the batch status will always return an empty rejected array.

Rate this page: