当前位置: 代码迷 >> 综合 >> django2 发送邮件配置,邮件内容使用html模板
  详细解决方案

django2 发送邮件配置,邮件内容使用html模板

热度:39   发布时间:2023-10-22 19:48:09.0

在 settings.py 的最后面加上类似这些

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_USE_TLS = False
EMAIL_HOST = 'smtp.tuweizhong.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'mail@tuweizhong.com'
EMAIL_HOST_PASSWORD = 'xxxx'
DEFAULT_FROM_EMAIL = 'mail@tuweizhong.com'

或者

# 发送邮件的setting设置
EMAIL_HOST = "smtp.163.com"     # 邮件服务器配置
EMAIL_PORT = 465
EMAIL_HOST_USER = "123123@163.com"         # 发件人邮箱账号
EMAIL_HOST_PASSWORD = "xxxxxx"       # 授权码
EMAIL_USE_TLS= True                         # 设置是否启用安全链接
EMAIL_FROM = "123123@163.com"              # 发件人邮箱

创建send_email.py文件

#!/usr/bin/python3
# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText# 引入项目settings邮箱配置
from djang_all.settings import (EMAIL_HOST,EMAIL_PORT,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,EMAIL_USE_TLS,EMAIL_FROM
)
from django.template import loaderdef send_email(email_to, content):"""自定义发送邮件(账号审核通过发送邮件):param email_to: 接收邮件邮箱:param content: 邮件内容:return:"""# 邮件内容加htmlbody = loader.render_to_string("send_email.html",    # 邮件里发送html(html模板){"content": content,    # html模板里面加变量})msg = MIMEText(body, 'html')msg['subject'] = u'=======邮件主题邮件主题======='       # 邮件主题msg['from'] = EMAIL_FROM        # 发件人msg['to'] = email_to            # 收件人try:s = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT)s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)s.sendmail(EMAIL_FROM, email_to, msg.as_string())print ('Done.sent email success')except smtplib.SMTPException:import tracebacktraceback.print_exc()print ('Error.sent email fail')

调用方法:

# 引入
from app.utils.send_email import send_emaildef index(request):...# 测试发送邮件to_email = '123123@qq.com'     # 接收人con = '123'                    # 内容send_email(to_email, con)...

邮件html模板,send_email.html ,加{ { content }} 即可

 

  相关解决方案