在 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 loader
def send_email(email_to, content):
"""
自定义发送邮件(账号审核通过发送邮件)
:param email_to: 接收邮件邮箱
:param content: 邮件内容
:return:
"""
# 邮件内容加html
body = 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 traceback
traceback.print_exc()
print ('Error.sent email fail')
调用方法:
# 引入
from app.utils.send_email import send_email
def index(request):
...
# 测试发送邮件
to_email = '123123@qq.com' # 接收人
con = '123' # 内容
send_email(to_email, con)
...
邮件html模板,send_email.html ,加{{ content }} 即可