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

前提条件

安装Python SDK核心库

  • 使用依赖包工具安装(推荐)
    • 如果您使用Python 2.x,执行以下命令,安装阿里云SDK核心库:
      pip install aliyun-python-sdk-core
    • 如果您使用Python 3.x,执行以下命令,安装阿里云SDK核心库:
      pip install aliyun-python-sdk-core-v3
  • 自行下载安装

    您可以使用git clone或其它手段下载aliyun-python-sdk-core并自行添加解决方案。下载安装包,请参见SDK 核心库

发送短信

  • 代码示例
    #!/usr/bin/env python
    #coding=utf-8
    
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkcore.request import CommonRequest
    from aliyunsdkcore.auth.credentials import AccessKeyCredential
    from aliyunsdkcore.auth.credentials import StsTokenCredential
    
    credentials = AccessKeyCredential('<your-access-key-id>', '<your-access-key-secret>')
    # use STS Token
    # credentials = StsTokenCredential('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
    client = AcsClient(region_id='cn-hangzhou', credential=credentials)
    
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')
    
    response = client.do_action(request)
    # python2:  print(response) 
    print(str(response, encoding = 'utf-8'))
  • 结果示例
    {  "RequestId": "614048FB-0619-4439-A1D5-AA8B218A****",  "Message": "OK",  "BizId": "386715418801811068^0",  "Code": "OK"}

相关文档

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