1. 导包模块
from django.core.mail import send_mail
2. 使用步骤
(1)settings.py配置发件人信息
配置可从配置文件读取,可从数据库读取,可写默认信息,根据自己使用场景配置
# 邮箱配置
email_path = os.path.join(BASE_DIR, "conf", "email_conf.json")
with open(email_path) as f:
email_conf = json.load(f)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = email_conf["tls"] # 是否使用TLS安全传输协议(用于在两个通信应用程序之间提供保密性和数据完整性。)
EMAIL_USE_SSL = email_conf["ssl"] # 是否使用SSL加密,qq企业邮箱要求使用
EMAIL_HOST = email_conf["host"] # 发送邮件的邮箱的SMTP服务器(smtp.qq.com)
EMAIL_PORT = email_conf["port"] # 发件箱的SMTP服务器端口(qq邮箱,ssl不加密时,端口为25)
# 发件人账号信息
EMAIL_HOST_USER = email_conf["user"] # 发件人的邮箱地址
EMAIL_HOST_PASSWORD = email_conf["password"] # 发送邮件的邮箱密码(这里使用的是授权码)
EMAIL_TO_USER_LIST = [] # 可选,用来配置收件人列表
(2) 简单发送邮件, util.py,封装方法
def send_email(subject, recipient_list, message="", html_message=""):
"""
:param subject: 邮件标题
:param message: 邮件内容,普通文本
:param recipient_list: 收件人,可以是多个
:param html_message: html邮件内容
:return:
"""
try:
info = read_conf(EMAIL_PATH)
params = {
"subject": subject,
"message": message,
"from_email": info["user"], # 发件人
"recipient_list": recipient_list,
"fail_silently": False, # 如果为False时,发送失败抛出错误
"html_message": html_message
}
if message: params.pop("html_message")
else: params["message"] = "收到邮件\n"
print(params)
send_mail(**params)
return True
except Exception:
print(traceback.format_exc())
return False
(3) 发送带附件的邮件,view.py示例
from django.shortcuts import render, HttpResponse
from django.core.mail import EmailMessage
def send_email(request):
"""发送带附件"""
msg = EmailMessage(
subject='这是带附件的邮件标题',
body='这是带附件的邮件内容',
from_email='', # 发件人
to=['123456789@qq.com'] # 收件人
)
msg.attach_file('exce.xls')
msg.send(fail_silently=False)
return HttpResponse('OK')
3. 非内置发送邮件
(1)smtp,此处不描述
(2)三方包yagmail
import yagmail # 第三方库
# 连接邮箱服务器
yag = yagmail.SMTP(user="9****@qq.com", password="****", host='smtp.qq.com')
# 邮箱正文
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
# 发送邮件
yag.send('18@163.com', 'subject', contents)
print("发送成功")
注意:收不到邮件时,查看下垃圾箱