结合腾讯云发送短信
4.1完整代码
#coding=gbk
import ssl
import random
ssl._create_default_https_context = ssl._create_unverified_context
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
# 获取云短信应用的appid和appkey
SDKAppID = '1400xxxx' #自己的ID
AppKey = '3b47d98800c5664034xxxx' #自己的APPKey
#签名
sms_sign = 'xx科技'
# 模板ID
template_id = '1367xxx' # 自己的template_id
# 输入的手机号
phone_number = '132xxxx' #自己的手机号
# 获取随机6位数
def captcha():
captcha = ''
for i in range(6):
now_number = str(random.randint(0, 9))
captcha += now_number
return captcha
# 发送手机号验证码
def send_pcode(captcha):
print('获取验证码',captcha)
ssender = SmsSingleSender(SDKAppID, AppKey)
# 模板中的参数,也就是{1}{2}这两个参数
params = [captcha] # 当模板没有参数时,`params = []`
try:
result = ssender.send_with_param(86, phone_number,
template_id, params, sign=sms_sign, extend="", ext="") # 签名参数不允许为空串
print(result)
except HTTPError as e:
print(e)
except Exception as e:
print(e)
if __name__ == '__main__':
send_pcode(captcha())
正则表达式实现
正则表达式强大、便捷、高效,但掌握起来有一定难度
import re
phone = input("请输入11位手机号码:")
pattern = re.compile(r'^(13[0-9]|14[0|5|6|7|9]|15[0|1|2|3|5|6|7|8|9]|'
r'16[2|5|6|7]|17[0|1|2|3|5|6|7|8]|18[0-9]|'
r'19[1|3|5|6|7|8|9])\d{8}$')
if pattern.search(phone):
print("手机号码合法!")
else:
Last updated