参考原文:Django笔记(Django邮件发送、Django邮箱验证码实现)
目录
单单发送邮件
邮件验证:
1.settings.py 配置(注意:要开启IMAP服务 才能发送邮件 ,在邮箱设置里的账户设置中)
# 邮件配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com' # 如果是 163 改成 smtp.163.com
EMAIL_PORT = 25 # 或者 995是设置了 SSL 加密方式
EMAIL_HOST_USER = '[email protected]' # 发送者账号
EMAIL_HOST_PASSWORD = '****' # 授权码(****)
EMAIL_USE_TLS = True # 必须开启
EMAIL_FROM = "[email protected]" # 发送者
2.url路由配置
urlpatterns = [
url(r'^send_many_email/$', v2.send_many_email), # 发送多封邮件
url(r'^send_my_email/$', v2.send_my_email), # 发送单封邮件
]
3.views 视图
from django.shortcuts import render,HttpResponse
from django.conf import settings
# django自带的邮件发送模块
from django.core.mail import send_mail,send_mass_mail
def send_many_email(requeset):
""" 发送多个人 """
title = "美团骑手offer" # 邮件标题
content1 = "该点外卖啦" # 邮件内容
email_from = settings.EMAIL_FROM # 发送者
reciever1 = [
'[email protected]', # 接收者
]
content2 = "吃饭睡觉不想敲代码"
# 邮件1
msg1 = (title, content1, email_from, reciever1)
# 邮件2
msg2 = ("渣渣们", content2, email_from, ['[email protected]', '[email protected]'])
send_mass_mail((msg1,msg2), fail_silently=True)
return HttpResponse("发送好了")
def send_my_email(req):
""" 发送单个人 """
title = "offer到达"
msg = "恭喜你成为美团骑手"
email_from = settings.EMAIL_FROM
reciever = [
'[email protected]'
]
# 发送邮件
ret = send_mail(title, msg, email_from, reciever)
print(ret)
return HttpResponse("ok")
1.setting配置同上面
2.url路径管理
urlpatterns = [
url(r'^verify/$', v2.verify), # 返回邮件确认页
url(r'^active/(?P.*)/$', v2.active), # 邮件确定请求路径
]
3.view 管理
import uuid
import hashlib
from django.conf import settings
from django.template import loader
from django.core.cache import cache
from django.core.mail import send_mail,send_mass_mail
def get_random_str():
"""设置随机"""
uuid_val = uuid.uuid4()
uuid_str = str(uuid_val).encode("utf-8")
md5 = hashlib.md5()
md5.update(uuid_str)
return md5.hexdigest()
def verify(req):
""" 发送邮件视图 """
if req.method == "GET":
return render(req, 'verify.html')
else:
param = req.POST
email = param.get('email')
# 生成随机字符
random_str = get_random_str()
# 拼接验证链接(加网址)
url = "http://127.0.0.1:8000/active/" + random_str+"/"
# 加载激活模板
tmp = loader.get_template('active.html')
# 渲染
html_str = tmp.render({'url': url})
title = "美团骑手offer"
msg = "我们给你发一个邮件"
email_from = settings.EMAIL_FROM
reciever = [
email,
]
# 将页面视图发送给接受者
send_mail(title, msg, email_from, reciever, html_message=html_str)
# 记录 token 对应的邮箱是谁 v k
cache.set(random_str, email, 120)
return HttpResponse('ok')
def active(req, random_str):
# 拿参数对应的缓存数据
res = cache.get(random_str)
if res:
# 通过邮箱找到对应用户
# 给用户的状态字段做更新,从未激活变成激活状态
return HttpResponse(res+"激活成功")
else:
return HttpResponse("验证链接无效")
4. template 管理
######## verify.html
Title
######## active.html
Title
欢迎注册 澳门赌城会员 想要体验 美女荷官
请点击 下面的连接