Sinch Developer Documentation

Building blocks to enable rich customer communication

Send an SMS to one or more ad-hoc recipients

In this tutorial, you'll learn the basics of sending an SMS from a Java application.

This tutorial will walk you through the steps to send an SMS using Sinch's Java SDK from a server or command line application.

Prerequisites

Before starting, please make sure that:

  • You have created your Sinch account
  • The right version of the JDK is installed on your computer
  • You have added the Sinch Java SDK JAR to your project

All details of those steps are available on the Java Getting Started page.

Send an SMS with Java

Create a connection to the REST API

The SDK requires you to first create an ApiConnection object that you will re-use for interacting with the API for the entire duration your application is running. This ApiConnection instance should be created once and closed when your application is shut down. It is not recommended and not efficient to create an ApiConnection instance for every interaction with the API.

An instance of the ApiConnection object can only be created using the ApiConnection.builder() method and its associated builder:

import com.clxcommunications.xms.ApiConnection;

ApiConnection connection = ApiConnection.builder()
        .servicePlanId("{YOUR_SERVICE_PLAN_ID}")
        .token("{YOUR_API_TOKEN}")
        .start();

Send an SMS to one or multiple recipients

Once an ApiConnection object is created and started, you can use it to interact with the API, such as sending an SMS message to one recipient:

import com.clxcommunications.xms.ClxApi;

connection.createBatch(ClxApi.batchTextSms()
        .sender("ignored")
        .addRecipient("{RECIPIENT_PHONE_NUMBER}")
        .body("Hello from Sinch!")
        .build());

Or sending the same message to multiple recipients:

import com.clxcommunications.xms.ClxApi;

connection.createBatch(ClxApi.batchTextSms()
        .sender("ignored")
        .addRecipient("{RECIPIENT_1_PHONE_NUMBER}")
        .addRecipient("{RECIPIENT_2_PHONE_NUMBER}")
        .body("Hello from Sinch!")
        .build());

Close the connection to the REST API when your application shuts down

When you're done using the ApiConnection or when your application is shutting down, you should stop the ApiConnection that was created to interact with the REST API:

connection.stop();

This is to ensure all resources created by the SDK such as the thread pool are stopped and freed.

There are multiple ways you can ensure the ApiConnection is closed:

  • try/finally statement

    If you're building a simple command line application, wrapping the code that interacts with the API in a try/finally block will ensure the connection is always closed:

ApiConnection connection = ApiConnection.builder()
        .servicePlanId("{YOUR_SERVICE_PLAN_ID}")
        .token("{YOUR_API_TOKEN}")
        .start();

try {
    // interact with the `connection` instance
} finally {
    connection.close();
}
  • try-with-resources statement (Java 8+)

    Because the ApiConnection implements the Closeable interface, it can be used in a try-with-resources statement as a simpler alternative to try/finally:

ApiConnection connection = ApiConnection.builder()
        .servicePlanId("{YOUR_SERVICE_PLAN_ID}")
        .token("{YOUR_API_TOKEN}")
        .start();

try (connection) {
    // interact with the `connection` instance
}
  • JVM Shutdown Hook

    Shutdown hooks allow you to execute code when the JVM is shutting down. Learn more about shutdown hooks)

  • JSR-250/330 @PreDestroy hooks

    Dependency Injection frameworks such as Spring, Guice or Picocontainer offer specific tools to execute code when the JVM is shutting down, such as the @PreDestroy annotation

Wrap up

To wrap up, here's the complete sources of a minimal Java application that starts a connection to the Sinch REST API, sends a message then closes the connection.

import com.clxcommunications.xms.ApiConnection;
import com.clxcommunications.xms.ApiException;
import com.clxcommunications.xms.ClxApi;
import com.clxcommunications.xms.api.MtBatchTextSmsResult;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SendMessage {
    private static final Logger log = Logger.getLogger(SendMessage.class.getName());

    private static final String SERVICE_PLAN_ID = "{YOUR_SERVICE_PLAN_ID}";
    private static final String API_TOKEN = "{YOUR_API_TOKEN}";
    private static final String RECIPIENT_PHONE_NUMBER = "{YOUR_PHONE_NUMBER}";

    public static void main(String[] args) throws IOException {

        ApiConnection conn = ApiConnection.builder()
                .servicePlanId(SERVICE_PLAN_ID)
                .token(API_TOKEN)
                .start();

        try {
            MtBatchTextSmsResult result =
                    conn.createBatch(ClxApi.batchTextSms()
                            .sender("ignored")
                            .addRecipient(RECIPIENT_PHONE_NUMBER)
                            .body("Hello from Sinch!")
                            .build());

            log.log(Level.INFO, "SMS sent with batch ID " + result.id());

        } catch (InterruptedException e) {
            log.log(Level.SEVERE, "Send interrupted.", e);
        } catch (ApiException e) {
            log.log(Level.SEVERE, "SMS could not be sent.", e);
        } finally {
            conn.close();  
        }
    }                
}

Edit on GitHub

Updated 2 months ago


Send an SMS to one or more ad-hoc recipients


In this tutorial, you'll learn the basics of sending an SMS from a Java application.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.