请看下面详细的讲解。
基于Python制作短信发送程序攻略
1. 准备工作
在制作短信发送程序前,需要一些准备工作。具体步骤如下:
1.1 注册开发者账号
在制作短信发送程序之前,需要注册一个开发者账号。以阿里云短信服务为例,注册链接为:
https://www.aliyun.com/product/sms?spm=5176.10695662.1176615.1.3a403e5fFAr7xS
注册成功后,需要创建一个短信签名和短信模板。具体步骤可参考阿里云官网文档:
https://help.aliyun.com/document_detail/121495.html
1.2 安装相关库
在Python中,常用的发送短信的库有aliyun-python-sdk-core
和aliyun-python-sdk-dysmsapi
。安装方式如下:
pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-dysmsapi
2. 发送短信
2.1 阿里云短信服务发送短信
阿里云短信服务发送短信的步骤如下:
- 导入相关库
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
- 设置请求参数
client = AcsClient('access_key_id', 'access_secret', 'default')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', "手机号")
request.add_query_param('SignName', "短信签名")
request.add_query_param('TemplateCode', "短信模板ID")
request.add_query_param('TemplateParam', "{'code':'123'}")
注意:access_key_id
和access_secret
需要替换成自己的。
- 发送请求并解析结果
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
2.2 示例1
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
client = AcsClient('access_key_id', 'access_secret', 'default')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', "18888888888")
request.add_query_param('SignName', "我的短信签名")
request.add_query_param('TemplateCode', "我的短信模板ID")
request.add_query_param('TemplateParam', "{'code':'123456'}")
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
2.3 示例2
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
client = AcsClient('access_key_id', 'access_secret', 'default')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', "16666666666")
request.add_query_param('SignName', "我的短信签名")
request.add_query_param('TemplateCode', "我的短信模板ID")
request.add_query_param('TemplateParam', "{'code':'789012'}")
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
以上就是基于Python制作短信发送程序的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于Python制作短信发送程序 - Python技术站