Azure Communication SMS Client Library for Python
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
-
azure.core.exceptions.HttpResponseError: (Unauthorized) The request couldn't be authenticated.
cause The connection string or Azure Active Directory credentials provided are invalid, expired, or lack necessary permissions.fixVerify that the `AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING` environment variable is correctly set and matches your Communication Services resource. If using AAD, ensure `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` are correct and the service principal has the 'Azure Communication Services Contributor' role. -
azure.core.exceptions.HttpResponseError: (Forbidden) The request was authorized, but has insufficient permissions to carry out this operation.
cause The authenticated identity does not have the necessary role-based access control (RBAC) permissions to send SMS messages.fixGrant the appropriate permissions, such as 'Azure Communication Services Contributor', to the identity being used for authentication on your Azure Communication Services resource. -
azure.core.exceptions.HttpResponseError: (InvalidInput) The request received couldn't be understood by the service. Double check the documentation and ensure you're sending everything required and in the correct format.
cause Typically caused by incorrect phone number formatting (not E.164) or unexpected/hidden characters in `from_`, `to`, or `message` fields.fixEnsure all phone numbers are in E.164 format (e.g., `+14255550123`). Trim and normalize all input strings to remove any invisible or non-printable characters. -
SmsSendResult.successful is False, SmsSendResult.error_message contains '5000 Message failed to deliver'
cause A generic SMS delivery failure, often due to carrier throttling, Azure Communication Services throughput limits, temporary network issues, or sending to an invalid/inactive phone number.fixReview best practices: implement retry logic with exponential backoff, send messages in batches, monitor ACS quotas, and ensure `from_` and `to` numbers are valid, mobile, and SMS-capable. Check if the recipient has opted out.
Warnings
- gotcha Phone numbers must be provided in the E.164 international standard format (e.g., +14255550123) for both `from_` and `to` parameters. Incorrect formats will lead to delivery failures.
- gotcha The Azure Communication Services resource and the associated phone number must be properly configured for SMS capabilities and verified. Toll-free numbers, in particular, require verification to avoid messages being blocked by carriers.
- gotcha Sending large volumes of SMS messages may encounter carrier throttling or Azure Communication Services throughput limits, resulting in delivery failures (e.g., '5000 Message failed to deliver').
- gotcha Authentication failures (e.g., `401 Unauthorized`, `403 Forbidden`) are common if the connection string is incorrect, environment variables for Azure Active Directory are missing, or the principal lacks sufficient permissions on the Communication Services resource.
Install
-
pip install azure-communication-sms
Imports
- SmsClient
from azure.communication.sms import SmsClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
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}")