Django內置email發送郵件
一、首先在settings.py文件設置相關參數
STATIC_URL = '/static/'
# 設置郵件域名
EMAIL_HOST = 'smtp.163.com'
# 設置端口號,爲數字
EMAIL_PORT = 25
#設置發件人郵箱
EMAIL_HOST_USER = 'xxxxx@163.com'
# 設置發件人 受權碼
EMAIL_HOST_PASSWORD = '本身的受權碼'
# 設置是否啓用安全連接
EMAIL_USER_TLS = True
# 以上這個配置信息,Django會自動讀取,
# 使用帳號以及受權碼進行登陸,
# 若是登陸成功,能夠發送郵件
二、回到views.py 文件,加入如下代碼
# 引入發送郵件的模塊
from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
from django.conf import settings
send_mail('關於中秋節放假通知',
'中秋節放三天假',
'qiqi1931@163.com',
['qiqi1931@163.com']
fail_silently = False)
# 值1:郵件標題 值2:郵件主人 值3:發件人 值4:收件人 值5:若是失敗,是否拋出錯誤
if res == 1:
return HttpResponse('郵件發送成功')
else:
return HttpResponse('郵件發送失敗')
三、多封給多我的進行發送
message1 = ('這個週日你有空嗎',
'孔子東遊見兩小兒便日',
'qiqi1931@163.com',
['891811395@qq.com', '819614513@qq.com'])
message2 = ('這個周 日你有空嗎?',
'孔子東遊,見兩小兒,便日',
'qiqi1931@163.com',
['891811395@qq.com', '1311173658@qq.com'])
res = send_mass_email((message1, message2))
if res == 2:
return HttpResponse('多封郵件發送成功')
else:
return HttpResponse('多封郵件發送失敗')
四、進階使用,多線程異步發送
import threading
from django.core.mail import send_mail
from django.conf import settings
class SendMail(threading.Thread):
def __init__(self,subject,text,email,fail_silently=False):
self.subject = subject
self.text = text
self.email = email
self.fail_silently = fail_silently
threading.Thread.__init__(self)
def run(self):
send_mail(
self.subject,
self.text,
settings.EMAIL_HOST_USER,
[self.email],
fail_silently=self.fail_silently
)
send_mail = SendMail(subject,text,email)
send_mail.start()