Django邮件发送
Posted siplips
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django邮件发送相关的知识,希望对你有一定的参考价值。
- 在settings中添加关键信息
EMAIL_HOST = ‘smtp.qq.com‘ #不同的邮箱有不同的发件地址(收件地址)
EMAIL_PORT = 25 #smtp端口号
EMAIL_HOST_USER = ‘邮箱‘ #发件人邮箱
EMAIL_HOST_PASSWORD = ‘密码‘ #邮箱密码,其实是授权码
2.在views中导入发邮件相关的包:
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail, send_mass_mail,EmailMultiAlternatives,BadHeaderError
from rest_framework.parsers import JSONParser
3.多种发邮件类型:
a.一封邮件发多人:send_mail,多人在列表里指定
b.多封邮件分别发多人:send_mass_mail,多套放在元组里
c.邮件中添加其他类型的内容:EmailMultiAlternatives、attach_alternative、send,制定了其他格式内容,原内容会被覆盖
4.综合案例:通过httpie等接口测试工具,post传递发邮件所需要的数据,并对逻辑做了处理,httpie默认传递json格式的数据,需要先解析成普通python基本数据类型,再进行操作(可用django自带的json loads dumps,也可用django框架restframework的parsers的JSONParser),导入的BadHeaderError用在请求数据有误时抛出无效的请求头 异常
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail, send_mass_mail,EmailMultiAlternatives,BadHeaderError
from rest_framework.parsers import JSONParser
# Create your views here.
def test01(request): # 一封邮件多发
send_mail(
‘这里是标题‘,
‘内容:天青色等烟雨‘,
‘邮箱‘,
[‘邮箱1‘, ‘邮箱2‘],
fail_silently=False,
)
return HttpResponse(‘OK‘)
def test02(request):
datatuple = (
(‘标题one‘, ‘内容one‘, ‘邮箱‘, [‘邮箱1‘, ‘邮箱2‘]),
(‘标题two‘, ‘内容two‘, ‘邮箱‘, [‘邮箱1‘, ‘邮箱2‘]),
)
send_mass_mail(datatuple,fail_silently=False)
return HttpResponse(‘OVER‘)
def test03(request):
subject,from_email,to = ‘哈哈主题‘,‘邮箱‘,[‘邮箱1‘, ‘邮箱2‘]
text_content = ‘红尘客栈‘
html_content = ‘<h1>红尘客栈风似刀,骤雨落宿命敲</h1>‘
msg = EmailMultiAlternatives(subject,text_content,from_email,to)
msg.attach_alternative(html_content,‘text/html‘)
msg.send()
return HttpResponse(‘html OVER‘)
def sendmail(request):
#用httpie测试接口时,默认传递过来的时json数据,所以需要先解析成python基本数据类型,再操作
if request.method == ‘POST‘:
data = JSONParser().parse(request)
subject = data.get(‘subject‘,‘‘)
message = data.get(‘message‘,‘‘)
from_email = data.get(‘from_email‘,‘‘)
if subject and message and from_email:
try:
send_mail(subject,message,from_email,[‘邮箱‘,])
except BadHeaderError:
return HttpResponse(‘Invalid header found.‘)
return HttpResponse(‘success OVER‘)
else:
return HttpResponse(‘Make sure all fields are entered and valid.‘)
return HttpResponse(‘GETGET‘)
以上是关于Django邮件发送的主要内容,如果未能解决你的问题,请参考以下文章