Quickstart: Send an SMS message

Important

Azure Communication Services is currently in public preview. This preview version is provided without a service-level agreement, and it's not recommended for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

Important

SMS messages can be sent to and received from United States phone numbers. Phone numbers located in other geographies are not yet supported by Communication Services SMS. For more information, see Plan your telephony and SMS solution.

Get started with Azure Communication Services by using the Communication Services C# SMS client library to send SMS messages.

Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run the dotnet command to check that the .NET client library is installed.
  • To view the phone numbers associated with your Communication Services resource, sign in to the Azure portal, locate your Communication Services resource and open the phone numbers tab from the left navigation pane.

Setting up

Create a new C# application

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name SmsQuickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

dotnet new console -o SmsQuickstart

Change your directory to the newly created app folder and use the dotnet build command to compile your application.

cd SmsQuickstart
dotnet build

Install the package

While still in the application directory, install the Azure Communication Services SMS client library for .NET package by using the dotnet add package command.

dotnet add package Azure.Communication.Sms --version 1.0.0-beta.3

Add a using directive to the top of Program.cs to include the Azure.Communication namespace.


using Azure.Communication;
using Azure.Communication.Sms;

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services SMS client library for C#.

Name Description
SmsClient This class is needed for all SMS functionality. You instantiate it with your subscription information, and use it to send SMS messages.
SendSmsOptions This class provides options to configure delivery reporting. If enable_delivery_report is set to True, then an event will be emitted when delivery was successful

Authenticate the client

Open Program.cs in a text editor and replace the body of the Main method with code to initialize an SmsClient with your connection string. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage you resource's connection string.

// This code demonstrates how to fetch your connection string
// from an environment variable.
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");

SmsClient smsClient = new SmsClient(connectionString);

Send an SMS message

Send an SMS message by calling the Send method. Add this code to the end of Main method in Program.cs:

smsClient.Send(
    from: new PhoneNumber("<leased-phone-number>"),
    to: new PhoneNumber("<to-phone-number>"),
    message: "Hello World via SMS",
    new SendSmsOptions { EnableDeliveryReport = true } // optional
);

You should replace <leased-phone-number> with an SMS-enabled phone number associated with your Communication Services resource and <to-phone-number> with the phone number you wish to send a message to.

The EnableDeliveryReport parameter is an optional parameter that you can use to configure Delivery Reporting. This is useful for scenarios where you want to emit events when SMS messages are delivered. See the Handle SMS Events quickstart to configure Delivery Reporting for your SMS messages.

Run the code

Run the application from your application directory with the dotnet run command.

dotnet run

Sample Code

You can download the sample app from GitHub

Get started with Azure Communication Services by using the Communication Services JavaScript SMS client library to send SMS messages.

Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run node --version to check that Node.js is installed.
  • To view the phone numbers associated with your Communication Services resource, sign in to the Azure portal, locate your Communication Services resource and open the phone numbers tab from the left navigation pane.

Setting up

Create a new Node.js Application

First, open your terminal or command window, create a new directory for your app, and navigate to it.

mkdir sms-quickstart && cd sms-quickstart

Run npm init -y to create a package.json file with default settings.

npm init -y

Use a text editor to create a file called send-sms.js in the project root directory. You'll add all the source code for this quickstart to this file in the following sections.

Install the package

Use the npm install command to install the Azure Communication Services SMS client library for JavaScript.

npm install @azure/communication-sms --save

The --save option lists the library as a dependency in your package.json file.

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services SMS client library for Node.js.

Name Description
SmsClient This class is needed for all SMS functionality. You instantiate it with your subscription information, and use it to send SMS messages.
SendSmsOptions This interface provides options to configure delivery reporting. If enable_delivery_report is set to true, then an event will be emitted when delivery was successful.
SendMessageRequest This interface is the model for building the sms request (eg. configure the to and from phone numbers and the sms content).

Authenticate the client

Import the SmsClient from the client library and instantiate it with your connection string. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage you resource's connection string.

Add the following code to send-sms.js:

const { SmsClient } = require('@azure/communication-sms');

// This code demonstrates how to fetch your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

// Instantiate the SMS client
const smsClient = new SmsClient(connectionString);

Send an SMS message

Send an SMS message by calling the send method. Add this code to the end of the send-sms.js:

async function main() {
  await smsClient.send({
    from: "<leased-phone-number>",
    to: ["<to-phone-number>"],
    message: "Hello World 👋🏻 via Sms"
  }, {
    enableDeliveryReport: true //Optional parameter
  });
}

main();

You should replace <leased-phone-number> with an SMS-enabled phone number associated with your Communication Services resource and <to-phone-number> with the phone number you wish to send a message to.

The enableDeliveryReport parameter is an optional parameter that you can use to configure Delivery Reporting. This is useful for scenarios where you want to emit events when SMS messages are delivered. See the Handle SMS Events quickstart to configure Delivery Reporting for your SMS messages.

Run the code

Use the node command to run the code you added to the send-sms.js file.


node ./send-sms.js

Get started with Azure Communication Services by using the Communication Services Python SMS client library to send SMS messages.

Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run the python --version command to check that Python is installed.
  • To view the phone numbers associated with your Communication Services resource, sign in to the Azure portal, locate your Communication Services resource and open the phone numbers tab from the left navigation pane.

Setting up

Create a new Python application

Open your terminal or command window, create a new directory for your app, and navigate to it.

mkdir sms-quickstart && cd sms-quickstart

Use a text editor to create a file called send-sms.py in the project root directory and add the structure for the program, including basic exception handling. You'll add all the source code for this quickstart to this file in the following sections.

import os
from azure.communication.sms import PhoneNumber
from azure.communication.sms import SendSmsOptions
from azure.communication.sms import SmsClient

try:
    # Quickstart code goes here
except Exception as ex:
    print('Exception:')
    print(ex)

Install the package

While still in the application directory, install the Azure Communication Services SMS client library for Python package by using the pip install command.

pip install azure-communication-sms

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services SMS client library for Python.

Name Description
SmsClient This class is needed for all SMS functionality. You instantiate it with your subscription information, and use it to send SMS messages.
SendSmsOptions This class provides options to configure delivery reporting. If enable_delivery_report is set to True, then an event will be emitted when delivery was successful

Authenticate the client

Instantiate an SmsClient with your connection string. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage you resource's connection string.

# This code demonstrates how to fetch your connection string
# from an environment variable.
connection_string = os.getenv('COMMUNICATION_SERVICES_CONNECTION_STRING')

# Create the SmsClient object which will be used to send SMS messages
sms_client = SmsClient.from_connection_string(connection_string)

Send an SMS message

Send an SMS message by calling the Send method. Add this code to the end of try block in send-sms.py:


# calling send() with sms values
sms_response = sms_client.send(
        from_phone_number=PhoneNumber("<leased-phone-number>"),
        to_phone_numbers=[PhoneNumber("<to-phone-number>")],
        message="Hello World via SMS",
        send_sms_options=SendSmsOptions(enable_delivery_report=True)) # optional property

You should replace <leased-phone-number> with an SMS enabled phone number associated with your communication service and <to-phone-number> with the phone number you wish to send a message to.

The send_sms_options parameter is an optional parameter that you can use to configure Delivery Reporting. This is useful for scenarios where you want to emit events when SMS messages are delivered. See the Handle SMS Events quickstart to configure Delivery Reporting for your SMS messages.

Run the code

Run the application from your application directory with the python command.

python send-sms.py

Get started with Azure Communication Services by using the Communication Services Java SMS client library to send SMS messages.

Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run mvn -v to check that maven is installed.
  • To view the phone numbers associated with your Communication Services resource, sign in to the Azure portal, locate your Communication Services resource and open the phone numbers tab from the left navigation pane.

Setting up

Create a new Java application

Open your terminal or command window and navigate to the directory where you would like to create your Java application. Run the command below to generate the Java project from the maven-archetype-quickstart template.

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

The 'generate' goal will create a directory with the same name as the artifactId. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model, or POM.

Install the package

Open the pom.xml file in your text editor. Add the following dependency element to the group of dependencies.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-sms</artifactId>
    <version>1.0.0-beta.3</version>
</dependency>

Set up the app framework

Add the azure-core-http-netty dependency to your pom.xml file.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-core-http-netty</artifactId>
    <version>1.3.0</version>
</dependency>

Open /src/main/java/com/communication/quickstart/App.java in a text editor, add import directives and remove the System.out.println("Hello world!"); statement:

package com.communication.quickstart;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import com.azure.communication.common.PhoneNumber;
import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.communication.sms.models.SendSmsOptions;
import com.azure.communication.sms.models.SendSmsResponse;
import com.azure.core.http.HttpClient;
import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;

public class App
{
    public static void main( String[] args ) throws IOException, NoSuchAlgorithmException, InvalidKeyException
    {
        // Quickstart code goes here
    }
}

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services SMS client library for Java.

Name Description
SmsClientBuilder This class creates the SmsClient. You provide it with endpoint, credential, and an http client.
SmsClient This class is needed for all SMS functionality. You use it to send SMS messages.
SendSmsResponse This class contains the response from the SMS service.
PhoneNumber This class holds phone number information

Authenticate the client

Instantiate an SmsClient with your connection string. The code below retrieves the endpoint and credential strings for the resource from environment variables named COMMUNICATION_SERVICES_ENDPOINT_STRING and COMMUNICATION_SERVICES_CREDENTIAL_STRING (Credential is the Key from the Azure portal. Learn how to manage you resource's connection string.

Add the following code to the main method:

// Your can find your endpoint and access key from your resource in the Azure Portal
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
String accessKey = "SECRET";

// Create an HttpClient builder of your choice and customize it
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();

// Configure and build a new SmsClient
SmsClient client = new SmsClientBuilder()
    .endpoint(endpoint)
    .accessKey(accessKey)
    .httpClient(httpClient)
    .buildClient();

You can initialize the client with any custom HTTP client the implements the com.azure.core.http.HttpClient interface. The above code demonstrates use of the Azure Core Netty HTTP client that is provided by azure-core.

You can also provide the entire connection string using the connectionString() function instead of providing the endpoint and access key.

// Your can find your connection string from your resource in the Azure Portal
String connectionString = "<connection_string>";
SmsClient client = new SmsClientBuilder()
    .connectionString(connectionString)
    .httpClient(httpClient)
    .buildClient();

Send an SMS message

Send an SMS message by calling the sendMessage method. Add this code to the end of main method:

List<PhoneNumber> to = new ArrayList<PhoneNumber>();
to.add(new PhoneNumber("<to-phone-number>"));

// SendSmsOptions is an optional field. It can be used
// to enable a delivery report to the Azure Event Grid
SendSmsOptions options = new SendSmsOptions();
options.setEnableDeliveryReport(true);

// Send the message and check the response for a message id
SendSmsResponse response = client.sendMessage(
    new PhoneNumber("<leased-phone-number>"),
    to,
    "<message-text>",
    options);

System.out.println("MessageId: " + response.getMessageId());

You should replace <leased-phone-number> with an SMS enabled phone number associated with your Communication Services resource and <to-phone-number> with the phone number you wish to send a message to.

The enableDeliveryReport parameter is an optional parameter that you can use to configure Delivery Reporting. This is useful for scenarios where you want to emit events when SMS messages are delivered. See the Handle SMS Events quickstart to configure Delivery Reporting for your SMS messages.

Run the code

Navigate to the directory containing the pom.xml file and compile the project using the mvn command.


mvn compile

Then, build the package.


mvn package

Run the following mvn command to execute the app.


mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

Troubleshooting

To troubleshoot issues related to SMS delivery, you can enable delivery reporting with Event Grid to capture delivery details.

Clean up resources

If you want to clean up and remove a Communication Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it. Learn more about cleaning up resources.

Next steps

In this quickstart, you learned how to send SMS messages using Azure Communication Services.