Django-发送邮件

概述

  • 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')
# longIO.delay()
# sendMail.delay()
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('验证失败')
本文结束 感谢您的阅读
正在加载今日诗词....