setting.py
EMAIL_HOST = 'smtp.qq.com'
EMAIL_HOST_USER = '(你的邮箱号码)'
EMAIL_HOST_PASSWORD = 'gilhwlbpdlydcaca' # 注意 这是发送短信生成的
导入
from django.core.mail import send_mail,send_mass_mail,EmailMultiAlternatives
(1)发送单封邮件
def sendMailOne(req):
send_mail(
'沙师弟',
'师傅又被抓走了',
'(你的邮箱地址)',
['对方邮箱地址'],
fail_silently=False,
)
return HttpResponse('发送邮件')
(2)发送更多封
def sendMailMany(req):
message1 = ('Subject here',
'<b>Here is the message</b>',
'你的邮箱.com',
['对方@qq.com',
'对方@qq.com'])
# message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])
send_mass_mail((message1,), fail_silently=False)
return HttpResponse('发送多封邮件')
之间的主要区别send_mass_mail()
和 send_mail()
是 send_mail()
打开每一个它的执行时间的邮件服务器的连接,同时send_mass_mail()
使用其所有消息的单个连接。这使得 send_mass_mail()
效率稍高
(3)发送html的邮箱
def sendHtmlMail(req):
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', '你的.com', '对方@qq.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return HttpResponse('发送html的文件内容')
(4)渲染模板进行邮件发送
#模板渲染邮件的发送
def sendTemMail(req):
subject, from_email, to = 'html', '你的.com', '对方.com'
html_content = loader.get_template('activate.html').render({'username':'张三'})
msg = EmailMultiAlternatives(subject, from_email=from_email, to=[to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return HttpResponse('发送html的文件内容')
active.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>欢迎:{{ username }}</h2>
<h3>请点击右侧激活地址 进行账户的激活 <a href="">激活</a></h3>
</body>
</html>