Azure Communication SMS Client Library for Python

1.1.0 · active · verified Thu Apr 16

The Azure Communication SMS client library for Python allows developers to integrate SMS messaging capabilities into their applications. It provides functionalities to send 1:1 and 1:N SMS messages via Azure Communication Services. The library is currently at version 1.1.0 and is part of the Azure SDK for Python, which typically sees regular updates, including new features and bug fixes, often on a monthly or bi-monthly cadence, alongside public preview releases for upcoming functionalities.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `SmsClient` using a connection string and send a single SMS message. It is crucial to replace placeholder environment variables with your actual Azure Communication Services connection string, and SMS-enabled phone numbers in E.164 format. The `enable_delivery_report` flag is set to `True` to allow tracking message delivery status.

import os
from azure.communication.sms import SmsClient

# Retrieve the connection string from an environment variable
# AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING is typically
# 'endpoint=https://<your-resource-name>.communication.azure.com/;accesskey=<your-access-key>'
connection_string = os.environ.get('AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING', 'YOUR_CONNECTION_STRING')

# Replace with your SMS enabled phone numbers
from_phone_number = os.environ.get('AZURE_COMMUNICATION_SERVICE_FROM_PHONE_NUMBER', '+1XXXXXXXXX') # E.164 format
to_phone_number = os.environ.get('AZURE_COMMUNICATION_SERVICE_TO_PHONE_NUMBER', '+1YYYYYYYYY')   # E.164 format

if connection_string == 'YOUR_CONNECTION_STRING':
    raise ValueError("Please set the AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING environment variable.")

if from_phone_number == '+1XXXXXXXXX':
    raise ValueError("Please set the AZURE_COMMUNICATION_SERVICE_FROM_PHONE_NUMBER environment variable.")

if to_phone_number == '+1YYYYYYYYY':
    raise ValueError("Please set the AZURE_COMMUNICATION_SERVICE_TO_PHONE_NUMBER environment variable.")

try:
    # Initialize the SmsClient with your connection string
    sms_client = SmsClient.from_connection_string(connection_string)

    # Send a 1:1 SMS message
    send_result = sms_client.send(
        from_=from_phone_number,
        to=[to_phone_number],
        message="Hello from Azure Communication Services!",
        enable_delivery_report=True
    )

    print(f"SMS message sent. Results: {send_result}")
    for result in send_result:
        if result.successful:
            print(f"  Message ID: {result.message_id}, To: {result.to}, Status: {result.http_status_code}")
        else:
            print(f"  Failed to send to {result.to}. Error: {result.error_message}, Status: {result.http_status_code}")

except Exception as ex:
    print(f"An error occurred: {ex}")

view raw JSON →