Python使用阿里云发送短信的两种方式

参考文档https://help.aliyun.com/document_detail/215764.html
安装依赖包

pip install alibabacloud_tea_openapi
pip install alibabacloud_dysmsapi20170525==2.0.9

第一种方式

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

def send_sms(mobile, code):
    # 短信验证
    client = AcsClient('ACCESS_KEY_ID','ACCESS_KEY_SECRET')
    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')
    request.add_query_param('RegionId', "cn-hangzhou")
    request.add_query_param('PhoneNumbers', mobile)
    request.add_query_param('SignName', "阿里云短信测试")   # 注意必须是审核通过的
    request.add_query_param('TemplateCode',"SMS_154950909")      # 注意必须是审核通过的
    request.add_query_param('TemplateParam', "{\"code\":\"%s\"}" % code)  # 你的验证码
    response = client.do_action_with_exception(request)
    print(code)

第二种方式

from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkcore.client import AcsClient
import uuid
from aliyunsdkcore.profile import region_provider

ACCESS_KEY_ID = ACCESS_KEY_ID
ACCESS_KEY_SECRET = ACCESS_KEY_SECRET
# 注意:不要更改
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"
acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)
region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)
sign_name = "阿里云短信测试"
template_code = "SMS_154950909"
def send_sms(business_id,phone_numbers,template_param):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)
    # 短信模板变量参数
    smsRequest.set_TemplateParam(template_param)
    # 设置业务请求流水号,必填。
    smsRequest.set_OutId(business_id)
    # 短信签名
    smsRequest.set_SignName(sign_name)
    smsRequest.set_PhoneNumbers(phone_numbers)
    # 调用短信发送接口,返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)
    # TODO 业务处理
    return smsResponse

if __name__ == '__main__':
    __business_id = uuid.uuid1()
    #print(__business_id)
    params = "{\"code\":\"2213\",}"
    print(send_sms( __business_id,"13800000000",params))

结果
在这里插入图片描述


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bbwangj/article/details/124102789