Django发送邮件方法
Posted iamluoli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django发送邮件方法相关的知识,希望对你有一定的参考价值。
在Django中将渲染后的模板进行邮件发送,可以使用send_email方法
首先在settings.py中添加如下配置
# 邮件配置SSL加密方式
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 465 # 使用SSL加密方式端口为465
EMAIL_HOST_USER = 'username@qq.com'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_USE_SSL = True # 使用SSL加密方式
EMAIL_FROM = 'username@qq.com'
# 邮件配置TTL加密方式
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 587 # 使用TTL加密方式端口为587
EMAIL_HOST_USER = 'username@qq.com'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_USE_TTL = True # 使用TTL加密方式
EMAIL_FROM = 'username@qq.com'
配置完成后,验证能够成功发送邮件
打开terminal,输入 python manage.py shell 打开shell,输入如下代码,如果返回值为1,则配置无误
from django.core.mail import send_mail
send_mail("Hello", "Hello World", "from_user@qq.com", ['to_user@qq.com'], 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, ['to_user@qq.com'])
以上是关于Django发送邮件方法的主要内容,如果未能解决你的问题,请参考以下文章