AI智能
改变未来

django:使用邮箱获取验证码

验证码用于判断当前用户与待验证用户是否i配,在注册、密码修改等需要身份验证的场景中有重要作用。
简单的验证方式有手机接受验证码和邮箱接收验证码。
这里主要将实现QQ邮箱验证。

1,开启第三方邮件发送服务

登录QQ邮箱网页版,点击顶部“设置”>>“账号”>>开启POP3/IMAP/SMTP服务>>生成授权码(注意保密

2,邮箱配置

EMAIL_USE_SSL = True
EMAIL_HOST = ‘smtp.qq.com’
EMAIL_PORT = 465
EMAIL_HOST_USER = ‘[email protected]
EMAIL_HOST_PASSWORD = ‘授权码’
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

3,模板文件

<!DOCTYPE html><html><head>{% load static %}<title>找回密码</title><link rel=\"stylesheet\" href=\"{% static \"css/reset.css\" %}\" /><link rel=\"stylesheet\" href=\"{% static \"css/user.css\" %}\" /><script src=\"{% static \"js/jquery.min.js\" %}\"></script><script src=\"{% static \"js/user.js\" %}\"></script></head><body><div class=\"page\"><div class=\"loginwarrp\"><div class=\"logo\">找回密码</div><div class=\"login_form\"><form id=\"Login\" name=\"Login\" method=\"post\" action=\"\">{% csrf_token %}<li class=\"login-item\"><span>用户名:</span><input type=\"text\" name=\"username\" class=\"login_input\"><span id=\"count-msg\" class=\"error\"></span></li>{% if password %}<li class=\"login-item\"><span>新密码:</span><input type=\"password\" name=\"password\" class=\"login_input\"><span id=\"password-msg\" class=\"error\"></span></li>{% endif %}{% if VCodeInfo %}<li class=\"login-item\"><span>验证码:</span><input type=\"text\" name=\"VCode\" class=\"login_input\"><span id=\"password-msg\" class=\"error\"></span></li>{% endif %}<div>{{ tips }}</div><li class=\"login-sub\"><input type=\"submit\" name=\"Submit\" value=\"{{ button }}\"></li></form></div></div></div><script type=\"text/javascript\">window.onload = function() {var config = {vx : 4,vy : 4,height : 2,width : 2,count : 100,color : \"121, 162, 185\",stroke : \"100, 200, 180\",dist : 6000,e_dist : 20000,max_conn : 10};CanvasParticle(config);}</script><script src=\"{% static \"js/canvas-particle.js\" %}\"></script></body></html>

4,视图函数

def findpsView(request):button = \'获取验证码\'	# 模板上下文:按钮提示内容VCodeInfo = False 	# 模板上下文:是否已发送验证码password = False	# 模板上下文:是否生成密码输入框if request.method == \'POST\':u = request.POST.get(\'username\')p = request.POST.get(\'password\')VCode = request.POST.get(\'VCode\', \'\') # 模板上下文:产生的验证码user = User.objects.filter(username=u)# 用户不存在if not user:tips = \'用户\' + u + \'不存在\'else:# 判断验证码是否已发送if not request.session.get(\'VCode\', \'\'):# 发送验证码并将验证码写入sessionbutton = \'重置密码\'tips = \'验证码已发送\'password = TrueVCodeInfo = TrueVCode = str(random.randint(000000, 999999))request.session[\'VCode\'] = VCodeuser[0].email_user(\'找回密码\', VCode)# 匹配输入的验证码是否正确elif VCode == request.session.get(\'VCode\'):# 密码加密处理并保存到数据库dj_ps = make_password(p, None, \'pbkdf2_sha256\')user[0].password = dj_psuser[0].save()del request.session[\'VCode\']tips = \'密码已重置\'# 输入验证码错误else:tips = \'验证码错误,请重新获取\'VCodeInfo = Falsepassword = Falsedel request.session[\'VCode\']return render(request, \'user.html\', locals())

收到邮件,重填密码就行。

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » django:使用邮箱获取验证码