一、在setting.py中加入邮件配置
+
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = '18570329382@163.com'
EMAIL_HOST_PASSWORD = 'zhang1991'
DEFAULT_FROM_EMAIL = 'laowu <18570329382@163.com'
二、邮件发送模块(project/email.py)
from __future__ import unicode_literals
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import render
def send_activate_mail(request,to, subject, template, **kwargs):
html = render(request, template+'.html',{'token':kwargs['token'],'username':kwargs['username']})
text = render(request, template+'.txt', {'token':kwargs['token'],'username':kwargs['username']})
msg = EmailMultiAlternatives(subject, text.content.decode('utf-8'), '18570329382@163.com', ['454995446@qq.com'])
msg.attach_alternative(html.content.decode('utf-8'), "text/html")
msg.send()
三、模型
from django.conf import settings
from django.db import models
# django密码转换
from django.contrib.auth.hashers import make_password
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired
from itsdangerous import BadSignature,SignatureExpired
# Create your models here.
class Users(models.Model):
nickname = models.CharField(max_length=16, null=False, blank=False, unique=True)
email = models.EmailField(max_length=32, null=False, blank=False, unique=True)
password = models.CharField(max_length=64, null=False, blank=False)
head = models.ImageField(default="decault.png")
age = models.CharField(max_length=3,blank=True,null=True)
sex = models.CharField(max_length=2, blank=True, null=True)
isactivate = models.BooleanField(default=False)
def save(self):
if not self.password.startswith('pbkdf2_'):
self.password = make_password(self.password)
super().save()
#生成token
def generate_activate_token(self, expires_in=360):
s = Serializer(settings.SECRET_KEY, expires_in)
return s.dumps({'id': self.id})
#token校验
@staticmethod
def check_activate_token(token):
s = Serializer(settings.SECRET_KEY)
try:
data = s.loads(token)
except BadSignature:
return '无效的激活码'
except SignatureExpired:
return '激活码已过期'
user = Users.objects.filter(id=data.get('id'))[0]
if not user:
return '激活的账号不存在'
if not user.isactivate:
user.isactivate = True
user.save()
return '激活成功'
四、视图函数
from django.shortcuts import render,HttpResponse
from django.views.generic import ListView
from django.contrib import messages
from user.forms import RegisterForm
from user.models import Users
# Create your views here.
from v2ex.email import send_activate_mail
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
u = Users()
u.nickname = form.cleaned_data['nickname']
u.email = form.cleaned_data['email']
u.password = form.cleaned_data['password']
u.age = form.cleaned_data['age']
u.sex = '男' if form.cleaned_data['sex']==0 else '女'
u.save()
token = u.generate_activate_token().decode('utf-8')
send_activate_mail(request, u.email, '激活账号', 'activate', token=token, username=u.nickname)
messages.add_message(request, messages.INFO, '账号注册成功,请前往邮箱激活账号!')
return render(request,'user_info.html',context={'user':u})
else:
return render(request, 'register.html',context={'form':form,'errors': form.errors})
else:
form = RegisterForm()
return render(request,'register.html',context={'form':form})
def login(request):
return render(request,'login.html')
def user_info(request):
return render(request,'user_info.html')
class UsersList(ListView):
model = Users
def activate(request):
token = request.GET['token']
result = Users.check_activate_token(token)
return HttpResponse(result)
五、urls配置,user/urls.py
from django.urls import path
from . import views
app_name = 'user'
urlpatterns = [
path(r'register/',views.register,name='register'),
path(r'login/',views.login,name='login'),
path(r'info/',views.user_info,name='info'),
path(r'activate/',views.activate,name='activate')
]
六、邮件模板(templates/email.html)
- email.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>账号激活</title>
</head>
<body>
<h1>Hello {{ username }}</h1>
<p>点击右边链接以完成激活,<a href="http://127.0.0.1:8000/user/activate/?token={{ token }}">激活</a></p>
</body>
</html>
- email.txt
点击右边链接以完成激活,<a href="http://127.0.0.1:8000/user/activate/?token={{token}}">激活