效果展示
实现逻辑:
- 前端验证邮箱输入框内是否是邮箱地址 (若不是 弹出提示框,否则下一步)
- 后端获取邮箱地址,生成验证码发送至对应邮箱, (若发送失败 弹出提示框,否则下一步)
- 获取验证码按钮开始倒计时 ,无法点击,等待用户输入
相关代码
-
前端HTML
<form id="form" name="form" class="form-horizontal col-md-offset-3 " style="margin-top:20px" > {% csrf_token %} <div class="form-group"> <label for="email" class="col-md-2 control-label">邮箱:</label> <div class="col-md-4"> <input type="text" name="email" id="email" class="form-control" placeholder="请输入你的邮箱"> </div> </div> <div class="form-group"> <label for="vertify" class="col-md-2 control-label">验证码:</label> <div class="col-md-4"> <div class="input-group"> <input type="text" name="vertify" id="vertify" class="form-control" placeholder="请输入校验码"> <span class="input-group-btn"> <input type="button" id="sendEmail" class="btn btn-default" value="获取验证码"> </span> </div> </div> </div> <div id="messBox" style="display: none;position: fixed; width: 300px;height: 35px; top:50%; left:40%; z-index:10; border-radius: 10%; background-color:#8c8c8c; color: white; text-align: center; "> <span id="errorMess" style="position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);"></span> </div>
-
前端邮箱验证js代码:
//展现显现错误提示信息 function showError(message) { document.getElementById("messBox").style.display="block"; $("#errorMess").html(message);//修改span标签内容 setTimeout("hidden()",2000); } //隐藏错误提示信息 function hidden() { document.getElementById("messBox").style.display="none";} //邮箱验证 function testEmail(str) { var re = /^\w+@[0-9a-z]+\.[a-z]+$/; return re.test(str); } $("#sendEmail").click(function () { var email = $("#email").val();//获取用户输入邮箱 if(email===''||!testEmail(email)) {//验证邮箱格式 showError('邮箱格式不正确,请重输');} else{ //按钮不可再次点击,开始倒计时 $.ajax({ url:"/member/reg", type:"post", data:{ type:'sendMessage', csrfmiddlewaretoken:'{{ csrf_token }}', email:email }, dataType :"json", success:function (reg) { // 短信发送失败 if(!reg.state){ showError(reg.errmsg);} else{ console.log(reg.state); settime();//短信发送成功,倒计时 } } }); var btn_sendEmail = $("#sendEmail"); var countdown=60; function settime() { if (countdown === 0) { btn_sendEmail.attr("disabled",false); btn_sendEmail.val("获取验证码"); return false; } else { btn_sendEmail.attr("disabled", true); btn_sendEmail.val("重新发送(" + countdown + ")"); countdown--; } setTimeout(function() { settime(); },1000); } } });
-
发送邮件setting配置
#邮件相关配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'# 发送邮件配置
EMAIL_HOST = 'smtp.qq.com'# 服务器名称
EMAIL_PORT = 25# 服务端口
EMAIL_HOST_USER = '1451284189@qq.com' # 邮箱
EMAIL_HOST_PASSWORD = 'dpbvxyovdsnmbaae'# 在邮箱中设置的客户端授权密码
EMAIL_FROM = '董*'# 收件人看到的发件人
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_USE_TLS = True #是否使用TLS安全传输协议
#EMAIL_USE_SSL = True #是否使用SSL加密,qq企业邮箱要求使用
- views文件
def sendMessage(email):#发送邮件并返回验证码
# 生成验证码
import random
str1 = '0123456789'
rand_str = ''
for i in range(0, 6):
rand_str += str1[random.randrange(0, len(str1))]
# 发送邮件:
# send_mail的参数分别是 邮件标题,邮件内容,发件箱(settings.py中设置过的那个),收件箱列表(可以发送给多个人),失败静默(若发送失败,报错提示我们)
message = "您的验证码是" + rand_str + ",10分钟内有效,请尽快填写"
emailBox = []
emailBox.append(email)
send_mail('怪奇物语', message, '1451284189@qq.com', emailBox, fail_silently=False)
return rand_str
# 验证该用户是否已存在 created = 1 存在
def existUser(email):
created = 1
try:
models.Member.objects.get(username=email)
except:
created = 0
return created
def reg(request):
if request.POST.get('type') == 'sendMessage':
print(request.POST.get('email'))
email = request.POST.get('email')
response = {"state": False, "errmsg": ""}
if existUser(email):
response['errmsg'] = '该用户已存在,请登录'
else:
try:
rand_str = sendMessage(email)#发送邮件
request.session['verify'] = rand_str # 验证码存入session,用于做注册验证
response['state'] = True
except:
response['errmsg'] = '验证码发送失败,请检查邮箱地址'
return HttpResponse(json.dumps(response))
-
路由分发
path('reg', views.reg),