Flask flask-mail
1、邮箱flask-mail
1.1、安装
pip install flask-mail
1.2、配置
ext.py
setting.py
# 邮箱服务器,这里我用的是163邮箱
MAIL_SERVER = "smtp.163.com"
# 端口
MAIL_PORT = 25
# 用于发送邮件的邮箱
MAIL_USERNAME = "*****************"
# 授权码
MAIL_PASSWORD = "**********"
# 默认发送者
MAIL_DEFAULT_SENDER = MAIL_USERNAME
1.3、测试
测试能不能发送
@blue.route('/sendmail/', methods=["GET", "POST"])
def send_mail():
# 参数依次为 主题 接收列表
msg = Message("flask email", recipients=["************@***.com", ])
# 内容
msg.body = "邮箱发送测试邮件"
# 默认html会覆盖body
msg.html = "<h2>flask发送邮件也很简单</h2>"
mail.send(message=msg)
return "邮件发送成功"
运行并访问
2、注册时短信激活
修改User模型,添加一个u_phone
迁移
python manage.py db migrate
python manage.py db upgrade
2.1、使用网易云信发送短信
网易云信地址
https://app.yunxin.163.com/index#/app
访问并登录:
查看开发手册
2.2、代码里的各种参数来源
url来源:开发者手册-请求说明
header来源:开发者手册-接口概述
"AppKey"来源: App Key管理-App Key
CheckSum来源:SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
AppSecret来源: App Key管理-App Key
2.3、开始写代码
@blue.route('/sendcode/')
def send_vcode():
url = "https://api.netease.im/sms/sendcode.action"
nonce = hashlib.new("sha512", str(time.time()).encode("utf-8")).hexdigest()
# time.time()默认有小数,所以这里我们转成int
curtime = str(int(time.time()))
sha1 = hashlib.sha1()
secret = "42557995027c"
sha1.update((secret + nonce + curtime).encode("utf-8"))
# hexdigest()返回摘要,作为十六进制数据字符串值
check_sum = sha1.hexdigest()
header = {
"AppKey": "26102a2d52e74ade21c2035f06dc6b06",
# 随机数,这里我们用时间然后哈希生成的一个数
"Nonce": nonce,
"CurTime": curtime,
"CheckSum": check_sum
}
phone = request.args.get("phone")
post_data = {
# 要发送的电话号码
"mobile": phone
}
r = requests.post(url, data=post_data, headers=header)
print(r.json())
return "发送成功"
运行并访问
手机收到的短信
prcharm后台
2.4、将验证码存入reids缓存
安装flask_caching
pip install flask_caching
配置
视图
@blue.route('/sendcode/')
def send_vcode():
url = "https://api.netease.im/sms/sendcode.action"
nonce = hashlib.new("sha512", str(time.time()).encode("utf-8")).hexdigest()
# time.time()默认有小数,所以这里我们转成int
curtime = str(int(time.time()))
sha1 = hashlib.sha1()
secret = "42557995027c"
sha1.update((secret + nonce + curtime).encode("utf-8"))
# hexdigest()返回摘要,作为十六进制数据字符串值
check_sum = sha1.hexdigest()
header = {
"AppKey": "26102a2d52e74ade21c2035f06dc6b06",
# 随机数,这里我们用时间然后哈希生成的一个数
"Nonce": nonce,
"CurTime": curtime,
"CheckSum": check_sum
}
phone = request.args.get("phone")
post_data = {
# 要发送的电话号码
"mobile": phone
}
r = requests.post(url, data=post_data, headers=header)
username = request.args.get("username")
r_json = r.json()
if r_json.get("code") == 200:
obj = r_json.get("obj")
cache.set(username, obj)
data = {
"msg": "ok",
"status": 200
}
return jsonify(data)
data = {
"msg": "失败",
"status": 400
}
return jsonify(data)