一、發送普通文本郵件
1、settings.py中的設置
# 發送郵件 # 發送郵件設置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False # 是否使用TLS安全傳輸協議 EMAIL_USE_SSL = True # 是否使用SSL加密,qq企業郵箱要求使用 # SMTP地址 EMAIL_HOST = 'smtp.qq.com' # SMTP端口 EMAIL_PORT = 465 # 自己的郵箱 EMAIL_HOST_USER = '776265xxxx@qq.com' # 自己的郵箱授權碼,非密碼 EMAIL_HOST_PASSWORD = 'qvsvaxxxxxxxxx' EMAIL_SUBJECT_PREFIX = '[迎風而來的博客]'
2、視圖函數實現發送文本
from django.shortcuts import render, HttpResponse from django.core.mail import send_mail def send_email(request): """ 發送郵件 :param request: :return: """ send_mail(subject='發送郵件的標題', message='發送郵件的內容', from_email='776265233@qq.com', #發送者郵箱 recipient_list=['1971956593@qq.com'], # 接收者郵箱可以寫多個 fail_silently=False) return HttpResponse('郵件發送成功')
二、發送帶有附件的郵件
1、settings.py中的設置
# 發送郵件 # 發送郵件設置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False # 是否使用TLS安全傳輸協議 EMAIL_USE_SSL = True # 是否使用SSL加密,qq企業郵箱要求使用 # SMTP地址 EMAIL_HOST = 'smtp.qq.com' # SMTP端口 EMAIL_PORT = 465 # 自己的郵箱 EMAIL_HOST_USER = '776265xxxx@qq.com' # 自己的郵箱授權碼,非密碼 EMAIL_HOST_PASSWORD = 'qvsvabxxxxxxxxxx' EMAIL_SUBJECT_PREFIX = '[迎風而來的博客]'
2、視圖函數實現發送附件
import os from django.conf import settings from django.core.mail import EmailMultiAlternatives from email.header import make_header def send_accessory_email(request): subject = '報告郵件' # 郵件主題 text_content = '這是一封重要的報告郵件.' # 郵件文本內容 html_content = '<p>這是一封<strong>重要的報告郵件</strong>.</p>' # 郵件主題內容樣式 from_email = settings.EMAIL_HOST_USER # 發送者郵箱 receive_email_addr = ["19719xxxxxx@qq.com"] # 接收者郵箱可以寫多個 msg = EmailMultiAlternatives(subject, text_content, from_email, receive_email_addr) msg.attach_alternative(html_content, "text/html") # 發送附件 file_path = r"C:\文件\附件.xlsx" # 發送附件的文件路徑 text = open(file_path, 'rb').read() file_name = os.path.basename(file_path) # 對文件進行編碼處理 b = make_header([(file_name, 'utf-8')]).encode('utf-8') msg.attach(b, text) # 傳入文件名和附件 msg.send() if msg.send(): return HttpResponse('郵件發送成功') else: return HttpResponse('郵件發送成功')