Django/Python发送HTML邮件 (包含图片)

Python中是如何发送邮件的,可以参考如下地址,很详细的:

python3之模块SMTP协议客户端与email邮件MIME对象 - Py.qi - 博客园

1.采用Django中的EmailMultiAlternatives发送html邮件,使用MIMEImage嵌入图片到邮件中。

from email.mime.image import MIMEImage
from django.core.mail import EmailMultiAlternatives

#拼接css
content_html = '''<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>Vinta</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2 user-scalable = yes">
    <style>
      table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
      }
      table td, table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
      }
      table th {
        background-color: #f1f1f1;
        border-bottom: 2px solid #ccc;
        text-align: center;
      }
      
    </style>
</head>
    <body>
        <p>第一张图片:</p>
        <img src="http://127.0.0.1:8000/auditImg/20220124/423f427f652645c2857fde98ecfed101.png" style="max-width:100%;" contenteditable="false"/>
        <table border="0" width="100%" cellpadding="0" cellspacing="0”>
	        <tbody>
		        <tr>
			        <th>test1</th>
			        <th>test2</th>
			        <th>test3</th>
			        <th>test4</th>
		        </tr>
		        <tr>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
		        </tr>
	        </tbody>
        </table>
        <p>第二张图片:</p>
        <img src="http://127.0.0.1:8000/auditImg/auditImg/20220124/e31b5d429e7b4a8793052eb6879f135c.png" style="max-width:100%;" contenteditable="false"/>

    </body>
</html>'''

def sendEmail(subject,content_html,from_email,to,cc)
    msg = EmailMultiAlternatives(subject = subject,body = content_html, from_email = from_email, to = to, cc = cc)

    msg.attach_alternative(content_html, "text/html")

    #处理html中的图片
    #由于保存的图片地址是http://127.0.0.1:8000/auditImg/20211021/2322211.png
    #真实的图片保存路径为static/img/detail/20211021/2322211.png     
    #所以需要转换一下路径,拿到图片地址 
    content_html =content_html.replace('src="http://127.0.0.1:8000/auditImg/','src="cid:')
    
    imgList = re.findall('src="cid:(.*?)"', html_content, re.S)
    print('imgList_____',imgList)
    for img in imgList:
        imgPath = os.path.join('static/img/detail',img)
        print(imgPath)
        image = add_img(imgPath,img)
        # msg.attach(image)

    try:
        msg.send()
    except Exception as e:
        print('send_mail exec error'+str(e))


def add_img(src, img_id):
    with open(src, 'rb') as f:
        msg_image = MIMEImage(f.read())
    msg_image.add_header('Content-ID', img_id)
    return msg_image

参考链接:

django中发送html邮件以及html中含有图片的邮件_随灬亦-CSDN博客

2.采用Python发送html邮件,嵌入图片,并添加附件。


import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart 

sender = 'Xiaoqian_Ma@pegatroncorp.com'        #发送邮箱
receivers = ['Xiaoqian_Ma@pegatroncorp.com']   #接受邮箱

message = MIMEMultipart('related')          #采用related定义内嵌资源的邮件体
message['Subject'] = '邮件标题。。。。。'
message['From'] = sender
message['To'] = ','.join(receivers)

#html内容
#拼接css
html_css_head = '''<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <style>
      table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
      }
      table td, table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
      }
      table th {
        background-color: #f1f1f1;
        border-bottom: 2px solid #ccc;
        text-align: center;
      }      
    </style>
</head>
<body>
<div id="content">'''

html_css_footer = '''</div></body></html>'''
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
<p>表格演示:</p>
<table>
<tr><th>第一列</th><th>第二列</th><th>第三列</th><th>第四列</th></tr>
<tr><td>h1</td><td>h2</td><td>h3</td><td>h4</td></tr>
<tr><td>d1</td><td>d2</td><td>d3</td><td>d4</td></tr>
</table>
"""
mail_msg = html_css_head + mail_msg + html_css_footer
msgtext = MIMEText(mail_msg,_subtype='html',_charset='utf-8')   #_subtype有plain,html等格式,避免使用错误
message.attach(msgtext)

# 指定图片为当前目录
fp = open('img.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
 
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)

#添加附件
filename = 'file.xlsx'
attachment='/Users/mac/Desktop/file.xlsx'
att1 = MIMEApplication(open(attachment, 'rb').read())
att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))  #注意:此处basename要转换为gbk编码,否则中文会有乱码。 
message.attach(att1)

#发送邮件
try:
    smtpObj = smtplib.SMTP('mail host',25)
    smtpObj.login("用户名","密码")
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发出的邮件如下:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值