概述
- Django内置了邮件发送功能,被定义在
django.core.mail
模块中。
- 发送邮件需要使用SMTP服务器,常用的免费服务器有163、126、QQ等。
注册并登陆163邮箱
打开POP3/SMTP服务与IMAP/SMTP服务
1 2 3 4 5 6 7 8 9 10
| EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25
EMAIL_HOST_USER = 'xxxxxxxxx@163.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_FROM = 'python<xxxxxxxxx@163.com>'
|
在settings.py
末尾添加以上代码
1 2 3 4
| url(r'^register/$', views.register), url(r'^send/$', views.send), url(r'^checkRegister/$', views.checkRegister)
|
视图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| from django.shortcuts import render from django.http import HttpResponse
def register(request): if request.method == 'GET': return render(request, 'myApp/register.html') else: username = request.POST.get('username') password = request.POST.get('password') send(request) return HttpResponse('注册成功!')
from django.conf import settings from django.core.mail import send_mail import uuid
def sendMail(request): msg = '<a href="http://127.0.0.1:8000/checkRegister/?check=123456">点击激活</a>' send_mail("注册激活", "", settings.EMAIL_FROM, ["xxxxxxxxx@qq.com"], html_message=msg) checkStr = str(uuid.uuid4()) request.session["check"] = checkStr
def send(request): sendMail(request) return HttpResponse("OK")
def checkRegister(request): checkStr = request.session.get("check", default=None) if checkStr: return HttpResponse(checkStr + '验证成功') else: return HttpResponse('验证失败')
|