Django——郵件傳送

抿嘴脣發表於2018-09-08
  1. 在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`)
 
 

相關文章