腾讯云短信
首先需要注册腾讯云账号,创建短信签名、模板等。 创建签名时,在腾讯云短信签名时需要认证,认证需要填写签名类型:网站、APP、小程序、公众号,前三种需要提供企业资质等复杂的东西,个人公众号认证会比较便捷,所以推荐个人开发的话使用 公众号 进行签名。 so,咱们需要先 申请一个公众号 然后 创建签名 。
如何发送短信?
# 1.安装SDK
pip install qcloudsms_py
# 2.基于SDK发送短信
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import ssl
# ssl._create_default_https_context = ssl._create_unverified_context
from qcloudsms_py import SmsMultiSender, SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
def send_sms_single(phone_num, template_id, template_param_list):
"""
单条发送短信
:param phone_num: 手机号
:param template_id: 腾讯云短信模板ID
:param template_param_list: 短信模板所需参数列表,例如:【验证码:{1},描述:{2}】,则传递参数 [888,666]按顺序去格式化模板
:return:
"""
appid = 666666 # 自己应用ID
appkey = "6666666666666666666" # 自己应用Key
sms_sign = "ChenihPython" # 自己腾讯云创建签名时填写的签名内容(使用公众号的话这个值一般是公众号全称或简称)
sender = SmsSingleSender(appid, appkey)
try:
response = sender.send_with_param(86, phone_num, template_id, template_param_list, sign=sms_sign)
except HTTPError as e:
response = {'result': 1000, 'errmsg': "网络异常发送失败"}
return response
# 2.发送短信视图函数
def sms(request):
"""
发送短信
?tpl=login -> 对应模板ID
?tpl=register -> 对应模板ID
"""
# 获取url中的tpl
tpl = request.GET.get('tpl')
# 由tpl获得所对应的value(模板id)
temlapte_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
if not temlapte_id:
return HttpResponse('模板不存在!')
# 随机出一个验证码
code = random.randrange(1000, 9999)
# 调用函数发送短信
res = send_sms_single('15399052423', temlapte_id, [code])
print(res)
if res['result'] == 0:
return HttpResponse('发送成功!')
else:
return HttpResponse(res['errmsg'])