安装:pip install flask-mail
官方文档:https://pythonhosted.org/Flask-Mail/
邮箱配置
MAIL_SERVER = 'smtp.qq.com' # 邮箱服务器地址
MAIL_PORT = 465 # 端口
MAIL_USE_TLS = True # 使用tls协议
MAIL_USERNAME = '1460@qq.com' # 邮箱
MAIL_PASSWORD = 'llahhie' # 邮箱授权码
MAIL_DEFAULT_SENDER = '14609@qq.com' # 默认发送者
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
db = SQLAlchemy()
mail = Mail()
发一封邮件测试一下
完成发送邮件功能
js
$(function () {
$('#captcha-btn').click(function (event) {
event.preventDefault();
var email = $('input[name="email"]').val();
console.log(email);
if(!email){
xtalert.alertInfoToast('请输入邮箱');
return;
}
http.get({
'url': '/cms/email_captcha/',
'data': {
'email': email
},
'success': function (data) {
if(data['code'] == 200){
xtalert.alertSuccessToast('邮件发送成功,请注意查收');
}else{
xtalert.alertInfo(data['message']);
}
},
'fail': function (error) {
xtalert.alertNetworkError();
}
});
});
});
引用
视图
@bp.route('/email_captcha/')
def email_captcha():
email = request.args.get('email')
if not email:
return restful.params_error('邮箱必填')
# 验证码
source = list(string.ascii_letters) # ['a-z','A-Z']
source.extend(map(lambda x: str(x), range(0, 10))) # ['a-z','A-Z', '0-9']
captcha = ''.join(random.sample(source, 6)) # 把随机取的6位列表转字符串当验证码
message = Message('CMS验证码', recipients=[email], body=f'验证码为:{captcha}')
try:
mail.send(message)
except:
return restful.server_error()
return restful.success()
触发