All Products
Search
Document Center

Short Message Service:Python SDK

Last Updated:Jun 23, 2026

Alibaba Cloud SMS SDK for Python provides a simple, secure interface for sending messages. It handles authentication, request signing, and HTTP communication so you can focus on your business logic.

Installation

System requirements

  • Python version: V3.7 or later.

  • Operating system: Windows, macOS, or Linux.

  • Other dependencies: alibabacloud_tea_openapi (core runtime), alibabacloud_tea_util (utility library), and urllib3 (HTTP client).

Install using pip

pip install alibabacloud_dysmsapi20180501

Verify the installation

import alibabacloud_dysmsapi20180501

# If the SDK version is printed, the installation is successful.
print("SDK Version:", alibabacloud_dysmsapi20180501.__version__)

Configure credentials

Step 1: Create a RAM user and grant permissions

Important

Your root account has full permissions. Use a RAM user for API calls and routine O&M. For more information, see Overview.

  • Create a RAM user: Go to the Create User page. Specify the required information, select Permanent AccessKey for Access Configuration, then click OK. Save your AccessKey for later use.

  • Grant permissions to the RAM User: Go to the Users page. Find the RAM user that you created and click Attach Policy in the Actions column. In the Policy search box, enter AliyunDysmsFullAccess, select the policy, and then click OK.

Note
  • AliyunDysmsFullAccess: Grants full permissions to manage the SMS service.

  • AliyunDysmsReadOnlyAccess: Grants read-only permissions to access the SMS service.

  • To create a custom policy, see RAM authorization.

Step 2: Configure access credentials

Store your AccessKey pair in environment variables. Configure environment variables on Linux, macOS, and Windows.

Note
  • Do not hard-code your AccessKey pair. Retrieve it from environment variables.

  • The sample code uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

Security best practices

  • Store credentials by using environment variables or a key management service.

  • Rotate your AccessKey pair on a regular basis.

  • Follow the principle of least privilege by granting the minimum required permissions to RAM Users.

  • Do not print credential information in logs.

  • Use a RAM Role instead of your root account credentials in production environments.

Quick start

Sample code

The following sample code shows how to call the SMS API to send messages. Replace the placeholder values as instructed in the code comments.

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json

from typing import List

from alibabacloud_dysmsapi20180501.client import Client as Dysmsapi20180501Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20180501 import models as dysmsapi_20180501_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


def create_client() -> Dysmsapi20180501Client:
    """
    Initializes a Client using credentials.
    @return: Client
    @throws Exception
    """
    # In production environments, we recommend a more secure authentication method that does not rely on an AccessKey pair. 
    credential = CredentialClient()
    config = open_api_models.Config(
        credential=credential
    )
    # The endpoint. Refer to https://api.alibabacloud.com/product/Dysmsapi
    config.endpoint = f'dysmsapi.aliyuncs.com'
    return Dysmsapi20180501Client(config)


def main(
    args: List[str],
) -> None:
    client = create_client()
    batch_send_message_to_globe_request = dysmsapi_20180501_models.BatchSendMessageToGlobeRequest(
        to='your_value',
        from_='your_value',
        message='your_value'
    )
    try:
        resp = client.batch_send_message_to_globe_with_options(batch_send_message_to_globe_request, util_models.RuntimeOptions())
        print(json.dumps(resp, default=str, indent=2))
    except Exception as error:
        # This code is for demonstration only. In production, handle exceptions properly and do not ignore them.
        # Error message
        print(error.message)
        # Diagnosis address
        print(error.data.get("Recommend"))


async def main_async(
    args: List[str],
) -> None:
    client = create_client()
    batch_send_message_to_globe_request = dysmsapi_20180501_models.BatchSendMessageToGlobeRequest(
        to='your_value',
        from_='your_value',
        message='your_value'
    )
    try:
        resp = await client.batch_send_message_to_globe_with_options_async(batch_send_message_to_globe_request, util_models.RuntimeOptions())
        print(json.dumps(resp, default=str, indent=2))
    except Exception as error:
        # This code is for demonstration only. In production, handle exceptions properly and do not ignore them.
        # Error message
        print(error.message)
        # Diagnosis address
        print(error.data.get("Recommend"))


if __name__ == '__main__':
    main(sys.argv[1:])

Download the sample code

Download and run the sample code directly.

  1. Go to SendMessageToGlobe.

  2. On the Parameters tab, specify the required parameters. Example values:

  • To: 88691567****

  • Message: This is a test message.

Best practices

Performance optimization

  • Enable connection pooling: The SDK uses the urllib3 connection pool by default. Make sure the max_idle_conns value is appropriate (default: 50) to avoid frequent TCP connection creation.

  • Use asynchronous calls: For high-concurrency scenarios, implement true asynchronous calls with asyncio and aiohttp (requires custom packaging).

Security recommendations

  • Enforce HTTPS: Always use an endpoint that starts with https://. Do not downgrade to HTTP.

  • Validate input: Validate all user inputs, such as phone_numbers (with regular expressions), template_param (by parsing JSON), and sign_name (against an allowlist).

  • Mask sensitive data in logs: When logging phone_numbers, apply log masking, such as 138****0000.

Resource management

  • Reuse the Client instance: The Client instance is thread-safe. Reuse a single instance throughout your application lifecycle to avoid unnecessary creation and teardown overhead.

  • Close resources: The SDK does not provide an explicit close() method. The underlying HTTP client automatically cleans up resources when the program exits.

References

  • Call an API:

    The SDK is the recommended way to call an API. This topic uses the Python SDK as an example. Other language SDKs follow a similar pattern. For more information, see SMS SDK.