Django 发送邮件以及html模板邮件
直接利用python的库发送邮件:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "username@gmail.com"
gmail_pwd = "password"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
if os.path.exists(attach):
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
mail("to_some@mail.com",
"Hello from python!",
"This is a email sent with python",
"my_picture.jpg")
django中发送html邮件:
# settings.py文件中添加配置:
# email config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # 这一项是固定的
EMAIL_HOST='smtp.gmail.com' # 对应的邮件服务商的smtp服务器地址 可百度
EMAIL_PORT = 25 # smtp服务固定的端口是25
EMAIL_HOST_USER='username@gmail.com' # 发送人的邮箱
EMAIL_HOST_PASSWORD='password' # 在邮箱中设置的客户端授权密码
EMAIL_USE_TLS = True
EMAIL_FROM = 'username@gmail.com' # 收件人看到的发件人 <此处要和发送邮件的邮箱相同>
# 发送邮件代码:
from django.core.mail import send_mail
send_mail('subject','body','username@gmail.com', ['to_some@mail.com'],fail_silently=True)
#(以上代码都经gmail邮箱测试通过)
django中发送html邮件:
#mailer.py
# -*- coding: utf-8 -*-
from django.core.mail import EmailMessage
from django.template import loader
from settings import EMAIL_HOST_USER #项目配置邮件地址,请参考发送普通邮件部分
def send_html_mail(subject, html_content, recipient_list):
msg = EmailMessage(subject, html_content, EMAIL_HOST_USER, recipient_list)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
subject = u'邮件主题'
html_content = loader.render_to_string(
template_path, #需要渲染的html模板
{
‘paramters’:paramters #参数
}
)
send_html_mail(subject, html_content, [收件人列表]):
官方文档:https://docs.djangoproject.com/zh-hans/2.1/topics/email/
参考: blog.sina.com.cn/s/blog_76e94d2101011bxd.html