使用 Django 来做一个电子邮箱注册 并 发送验证码的功能 (此处以 163 邮箱为例)
一. 登陆 163 邮箱账号, 然后进行下列操作
二. settings 配置文件
# 发送邮箱验证码 EMAIL_HOST = "smtp.163.com" # 服务器 EMAIL_PORT = 25 # 一般情况下都为25 EMAIL_HOST_USER = "[email protected]" # 账号 EMAIL_HOST_PASSWORD = "******" # 密码 (注意:这里的密码指的是授权码) EMAIL_USE_TLS = False # 一般都为False EMAIL_FROM = "[email protected]" # 邮箱来自
三. 添加电子邮箱验证 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"2. 邮箱验证码" verbose_name_plural = verbose_name def __unicode__(self): return '{0}({1})'.format(self.code, self.email)
四. 发送邮件工具 email_send.py
from random import Random # 用于生成随机码 from django.core.mail import send_mail # 发送邮件模块 from app01.models import EmailVerifyRecord # 邮箱验证model from django.conf import settings # setting.py添加的的配置信息 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 email: 要发送的邮箱 :param send_type: 邮箱类型 :return: True/False """ email_record = EmailVerifyRecord() # 将给用户发的信息保存在数据库中 code = random_str(16) 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
五. 在你的获取验证码的接口中直接调用上面方法即可。例如 发送注册码
# 注册发送邮箱验证码 class SendEmailRegisterCodeView(APIView): def get(self, request, *args, **kwargs): return redirect('/register') def post(self, request, *args, **kwargs): ret = BaseResponseData() try: email = request.POST.get("email", None) ret.data = { 'code': "0",'email': email,'error_email': '' } user_obj = models.MembershipAccount.objects.filter(username=email, is_active=True).first() if user_obj: ret.data['code'] = "111" ret.data['error_email'] = "用户已存在" return Response(ret.dict) else: # 发送邮箱 res_email = send_code_email(email) if res_email: # 注册用户信息,设置登陆状态为False create_last_user = models.MembershipAccount.objects.update_or_create(username=email, is_active=False) if not create_last_user: ret.data['code'] = "111" ret.data['error_email'] = "注册错误,请重试" return Response(ret.dict) return Response(ret.dict) else: ret.data['code'] = "111" ret.data['error_email'] = "验证码发送失败, 请稍后重试" return Response(ret.dict) except Exception as e: print("错误信息 : ", e) ret.data['code'] = "111" ret.data['error_email'] = "验证错误, 请稍后重试" return Response(ret.dict)