Django 发送邮件以及html模板邮件

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值