在django中提供了邮件接口
QQ邮箱配置
qq邮箱地扯:https://mail.qq.com
settings文件
# 邮箱配置
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.qq.com' # 如果是 163 改成 smtp.163.com
EMAIL_PORT = 465
EMAIL_HOST_USER = 'xxxx@qq.com' # 配置邮箱
EMAIL_HOST_PASSWORD = 'xxxxx' # 对应的授权码
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
邮箱发送视图
普通信息邮件发送
# 引入相关模块
from django.conf import settings
from django.core.mail import send_mail
def send_mail(request):
msg = '测试django发送邮箱'
send_mail(
subject='请注意这是Django邮件测试',
message=msg,
from_email=settings.EMAIL_HOST_USER,
recipient_list=["xxxx@qq.com"] # 把这条邮件信息发送给xxxx@qq.com的邮箱
)
return HttpResponse('测试邮件已发出请注意查收')
路由
path("check_mail", views.check_mail, name='check_mail'),
模板html邮件发送
第一步:创建要发送的模板html
在templates下创建一个文件夹mail,mail文件夹里有一个文件:send_html.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送Html</title>
</head>
<body>
<b>模板Html邮箱发送,接收的参数是:{{ paramters }}</b>
</body>
</html>
第二步:创建一个包utils
utils包里创建mail.py文件,内容如下:
from django.conf import settings
from django.core.mail import send_mail, EmailMessage
from django.template import loader
# 发送模板信息邮件
def send_html_mail(subject, html_content, recipient_list):
msg = EmailMessage(subject, html_content, settings.EMAIL_HOST_USER, recipient_list)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
第三步:视图文件
关键内容如下:
# 引入相关模块
from django.core.mail import send_mail
from utils.mail import send_html_mail
from django.template import loader
def send_html(request):
subject = "发送html模板邮箱信息"
html_content = loader.render_to_string('mail/send_html.html',{'paramters':'demo'})
recipient_list = ["xxx@qq.com"] # 发给xxx@qq.com的邮箱
send_html_mail(subject,html_content,recipient_list)
return HttpResponse('发送成功:已发送模板信息')
第四步:路由
path("send_html", views.send_html, name='send_html'),
注意地方:
如果发送成功收不到邮件信息的话,请查看邮箱中的垃圾箱,如下图:
==================== 完,最后自己查看 ===============================