All Products
Search
Document Center

Short Message Service:Python SDK

Last Updated:Mar 06, 2026

Alibaba Cloud SMS SDK for Python provides a simple, secure interface for core APIs such as sending messages . It abstracts away the complexities of authentication, request signing, and HTTP communication, so you can focus on your business logic and integrate SMS capabilities faster.

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

Because your root account has high privileges, we recommend using a RAM user for API calls and routine O&M. For more information, see Overview of RAM users.

  • 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.

  • If you need to create a custom policy, see RAM authorization.

Step 2: Obtain access credentials

Configure your AccessKey pair using environment variables. For information about how to configure environment variables, see Configure environment variables on Linux, macOS, and Windows.

Note
  • To prevent security risks, avoid hard-coding your AccessKey pair. Instead, retrieve it from environment variables.

  • The sample code in this topic 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

This sample code demonstrates 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

You can also download the sample code and run it directly.

  1. Go to SendMessageToGlobe.

  2. On the Parameters tab on the left, specify the required parameters. The following are 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. Ensure that the max_idle_conns configuration is appropriate (default is 50) to avoid frequent creation of TCP connections.

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

Security recommendations

  • Enforce HTTPS: Always use an endpoint that starts with https://. Avoid downgrading to HTTP.

  • Validate input: Strictly validate all user inputs, such as phone_numbers (by using regular expressions), template_param (by parsing JSON), and sign_name (by using 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. We recommend globally reusing a single instance throughout your application's lifecycle to avoid frequently creating and destroying it.

  • Close resources: Although 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. SDK usage in other languages is similar. For more information, see SMS SDK.