本文为您介绍短信服务Python SDK的使用方法及示例。

准备工作

  • 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问密钥(AccessKey)。详情请参见AccessKey
  • 安装SDK。
    pip install alibabacloud_dysmsapi20170525

发送短信

  • 代码示例
    import sys
    
    from typing import List
    
    from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client(
            access_key_id: str,
            access_key_secret: str,
        ) -> Dysmsapi20170525Client:
            """
            使用AK&SK初始化账号Client
            @param access_key_id:
            @param access_key_secret:
            @return: Client
            @throws Exception
            """
            config = open_api_models.Config(
                # 您的AccessKey ID,
                access_key_id=access_key_id,
                # 您的AccessKey Secret,
                access_key_secret=access_key_secret
            )
            # 访问的域名
            config.endpoint = 'dysmsapi.aliyuncs.com'
            return Dysmsapi20170525Client(config)
    
        @staticmethod
        def main(
            args: List[str],
        ) -> None:
            client = Sample.create_client('accessKeyId', 'accessKeySecret')
            send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
                phone_numbers='1503871****',
                sign_name='阿里大于测试专用',
                template_code='SMS_209335004',
                template_param='{"code":"1111"}'
            )
            # 复制代码运行请自行打印 API 的返回值
            client.send_sms(send_sms_request)
    
        @staticmethod
        async def main_async(
            args: List[str],
        ) -> None:
            client = Sample.create_client('accessKeyId', 'accessKeySecret')
            send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
                phone_numbers='15038712376',
                sign_name='阿里大于测试专用',
                template_code='SMS_209335004',
                template_param='{"code":"1111"}'
            )
            # 复制代码运行请自行打印 API 的返回值
            await client.send_sms_async(send_sms_request)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
                        
  • 结果示例
    {  "RequestId": "614048FB-0619-4439-A1D5-AA8B218A****",  "Message": "OK",  "BizId": "386715418801811068^0",  "Code": "OK"}

相关文档

  • 如果您想了解更多示例,请参见OpenAPI开发者门户
    说明 登录开发者门户平台,SDK版本选择时,请选择升级版 SDK
  • 短信服务相关API,请参见API概览