一、前言
1、邮箱有几种类型?
邮箱分为企业邮箱,如:腾讯企业邮箱、网易企业邮箱、阿里企业邮箱、新浪企业邮箱、zoho企业邮箱。个人邮箱,如:QQ邮箱、163网易邮箱、sina新浪邮箱。
2、TCL&SSL是什么?
django中发送邮件,我们一般使用SMTP服务。SMTP发送邮件时常用的协议有TCL和SSL。 zoho企业邮箱的常用配置(出意味着发送邮件),如下:
3、django授权码?
在django下利用SMTP发送邮件时我们会关注到授权码这个字眼,在我利用到企业邮箱发送邮件以后,我才了解到,企业邮箱是没有授权码字眼的,所谓的的授权码,相对个人邮箱而言是开启SMTP服务时设置的一串字符。 那么,在django中,企业邮箱发送邮件setting配置EMAIL_HOST_PASSWORD应使用是什么呢?其实就是我们登录企业邮箱时的密码。
二、邮箱配置
1、自行百度 2、个人邮箱而言,需要开启SMTP服务,拿到授权码。 3、企业邮箱而言,设置中查看参数
三.settings 配置
EMAIL_HOST = 'smtp.xxx.com'
EMAIL_PORT = 123
EMAIL_HOST_USER = "xxx@yyy.com"
EMAIL_HOST_PASSWORD = "********"
EMAIL_FROM = EMAIL_HOST_USER
EMAIL_USE_SSL = True
四、添加电子邮箱验证 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
from django.conf import settings
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 = "您的邮箱注册验证码为:{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:
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)
|