Django邮件发送
程序员文章站
2022-03-28 19:02:28
EMAIL_HOST = 'smtp.qq.com' #不同的邮箱有不同的发件地址(收件地址) EMAIL_PORT = 25 #smtp端口号 EMAIL_HOST_USER = '邮箱' #发件人邮箱 EMAIL_HOST_PASSWORD = '密码' #邮箱密码,其实是授权码 2.在view ......
- 在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')