【问题描述】使用Python如何发送手机短信呢?
【小千解答】可以调用各云厂商提供的短信服务API,以阿里云为例。
Stage 01 > 准备工作
1、购买短信套餐包
2、新建签名,比如【小千办公】
3、新建短信模版,比如:邮箱开通通知
模版code:QQ_1695716607
模版内容:亲爱的${clarkname},欢迎你的加入!专属邮箱${emailaddr}已开通,密匙${emailpwd},预祝使用愉快!
变量属性:clarkname-其他;emailaddr-其他;emailpwd-其他号码
4、获取AccessKey ID和AccessKey Secret
Stage 02 > 安装模块
pip install alibabacloud_dysmsapi20170525
Stage 03 > 编写代码
示例如下:
from alibabacloud_dysmsapi20170525.client import Client as DysmsapiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_dysmsapi20170525 import models as dysmsapi_models class cls_SMS: def __init__(self): pass @staticmethod def create_client( access_key_id: str, access_key_secret: str, ) -> DysmsapiClient: config = open_api_models.Config() config.access_key_id = access_key_id config.access_key_secret = access_key_secret return DysmsapiClient(config) @staticmethod def xq_sms(phoneno,signname,tplcode,tplvars): client = cls_SMS.create_client('xqoffice-key-id','xqoffice-key-secret') send_req = dysmsapi_models.SendSmsRequest( phone_numbers = phoneno, sign_name = signname, template_code = tplcode, template_param = tplvars ) send_resp = client.send_sms(send_req) return send_resp.body.message phone_num = '15212345678' sign_name = '小千办公' tpl_code = 'QQ_1695716607' name = "胡丽晶" address = "fox-girl@xqoffice.cn" password = "Wuya74" tpl_vars = '{"clarkname":"%s","emailaddr":"%s","emailpwd":"%s"}' % (name,address,password) xq_val = cls_SMS.xq_sms(phone_num,sign_name,tpl_code,tpl_vars) if xq_val != 'OK': print('发送失败!')