在Django中将渲染后的模板进行邮件发送,可以使用send_email方法
首先在settings.py中添加如下配置
# 邮件配置SSL加密方式
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 465 # 使用SSL加密方式端口为465
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_USE_SSL = True # 使用SSL加密方式
EMAIL_FROM = '[email protected]'
# 邮件配置TTL加密方式
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 587 # 使用TTL加密方式端口为587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_USE_TTL = True # 使用TTL加密方式
EMAIL_FROM = '[email protected]'
配置完成后,验证能够成功发送邮件
打开terminal,输入 python manage.py shell 打开shell,输入如下代码,如果返回值为1,则配置无误
from django.core.mail import send_mail
send_mail("Hello", "Hello World", "[email protected]", ['[email protected]'], fail_silently=False)
在views中编辑如下代码
from django.core.mail import EmailMessage
from django.template import loader
from settings import EMAIL_HOST_USER
import os
def send_html_mail(cls, subject, html_content, recipient_list):
"""
发送邮件
:param html_content:
:param recipient_list:
:return:
"""
msg = EmailMessage(subject, html_content, EMAIL_HOST_USER, recipient_list)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates', 'report.html')
parameters = {'report_title':"this is a test report"}
subject = u'邮件主题'
html_content = loader.render_to_string(
TEMPLATE_PATH,
{
'parameters': parameters
}
)
send_html_mail(subject, html_content, ['[email protected]'])
原文地址:https://www.cnblogs.com/iamluoli/p/11479854.html
时间: 2024-10-28 10:34:36