设置邮箱
邮箱设置1邮箱设置2
setting文件
#邮箱设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# 发送邮箱验证码
EMAIL_HOST = 'smtp.163.com' # 服务器
EMAIL_PORT = 25 # 一般情况下都为25
EMAIL_HOST_USER = "yeyangfengqi@163.com" # 账号
EMAIL_HOST_PASSWORD = "*******" # 密码 (注意:这里的密码指的是授权码)
EMAIL_USE_TLS = True # 一般都为False
EMAIL_FROM = "yeyangfengqi@163.com" # 邮箱来自
#end邮箱设置
用于存放验证码的model
记得注册你的项目中
# 邮箱验证
class EmailVerifyRecord(models.Model):
# 验证码
code = models.CharField(max_length=20, verbose_name="验证码")
email = models.EmailField(max_length=50, verbose_name="邮箱")
# 包含注册验证和找回验证
send_type = models.CharField(verbose_name="验证码类型", max_length=10,
choices=(("register", "注册"), ("forget", "找回密码")))
send_time = models.DateTimeField(verbose_name="发送时间", default=datetime.datetime.now())
class Meta:
verbose_name = u"邮箱验证码"
verbose_name_plural = verbose_name
def __unicode__(self):
return '{0}({1})'.format(self.code, self.email)
#end邮箱验证
发送邮件脚本编写 emial_send.py
# @Time : 2019/9/20 9:32
# @Author : Yeyangfengqi
# @Site :
# @File : email_send.py.py
# @Software: PyCharm
# @effect : 邮件发送
from random import Random # 用于生成随机码
from django.core.mail import send_mail # 发送邮件模块
from django.conf import settings # setting.py添加的的配置信息
from ..models import EmailVerifyRecord # 邮箱验证model
import datetime
# 生成随机字符串
def random_str(randomlength=8):
"""
随机字符串
:param randomlength: 字符串长度
:return: String 类型字符串
"""
str = ''
# 验证码包含字符
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
# 随机产生字符
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str
def send_code_email(email, send_type='register'):
"""
:param emial:
:param send_type:
:return: True/False
"""
#实例化表
email_record = EmailVerifyRecord()
# 将给用户发的信息保存在数据库中
#获取随机验证码
code = random_str(8)
#保存验证码
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.send_time = datetime.datetime.now()
email_record.save()
# 初始化为空
email_title = ""
email_body = ""
# 判断使用邮箱类型
# 如果为注册类型
if send_type == "register":
email_title = "注册激活"
# email_body = "请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}".format(code)
email_body = "您的邮箱注册验证码为:{0}, 该验证码有效时间为两分钟,请及时进行验证。".format(code)
#发送邮件
send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
if not send_status:
return False
if send_type == "retrieve":
email_title = "找回密码"
email_body = "您的邮箱注册验证码为:{0}, 该验证码有效时间为两分钟,请及时进行验证。".format(code)
# 发送邮件
send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
if not send_status:
return False
return True
view视图中的使用
使用前记得导入emial_send.py
定义发送函数
def user_register_send_emial(request):
if request.method == "GET":
email = request.GET.get('email', default='')
send_code_email(email)
message = "发送成功"
return JsonResponse({"state": True, "message": message})
在url中添加path
path('register_send_emial', views.user_register_send_emial, name='register_send_emial'),
使用时,在前端点击按钮,ajax请求这个路径,就可以直接发送邮件了。
验证验证码
def user_register(request):
if request.method == "POST":
#获取前端json数据
postBody = json.loads(request.body)
#赋值
email, username, pwd1, pwd2, smscode = postBody['email'], postBody['username'], postBody['pass'], postBody['checkPass'], postBody['smscode']
#验证码过期时间,思路是当前时间的前1个小时内的验证码
check_time = datetime.datetime.now() - datetime.timedelta(hours=1)
#查询验证码数据
check_smscode = EmailVerifyRecord.objects.filter(code=smscode).filter(email=email).filter(send_time__gt=check_time).filter(send_type='register')
#如果不存在,返回错误
if (check_smscode):
pass
else:
message = "验证码错误!"
return JsonResponse({"state": False, "message": message})
使用效果
后端使用效果前端是我用Vue写的,直接跳转到登陆界面了。。。
前端效果
网友评论