Python3发送带图邮件

版权声明:原创文章,未经允许不得转载。www.data-insights.cn | www.data-insight.cn | https://blog.csdn.net/qixizhuang/article/details/84657707

我们常常会遇到需要通过脚本添加监控的情况,一般我们会选择使用邮件的方式通知相关人员。

一个简单的邮件我们可以轻松构建出来(可以参考我之前的文章《Python3使用smtplib发送邮件》),但是有些时候在邮件中增加一个图片往往能起到事半功倍的效果,毕竟一图胜千言嘛。

今天我们就看下如何在邮件中添加图片信息。

# -*- coding: utf8  -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import smtplib
import matplotlib.pyplot as plt


if __name__ == '__main__':
    # 以html格式构建邮件内容
    send_str = '<html><body>'
    send_str += '<center>下边是一张图片</center>'
    
    # html中以<img>标签添加图片,align和width可以调整对齐方式及图片的宽度
    send_str += '<img src="cid:image1" alt="image1" align="center" width=100% >'
    send_str += '<center>上边是一张图片</center>'
    send_str += '</body></html>'
    
    # 画图并保存到本地
    pic_path = 'test.png'
    plt.plot([1,3,2,4], '--r')
    plt.title('这是一个测试')
    plt.savefig(pic_path)

    # 构建message
    msg = MIMEMultipart()
    
    # 添加邮件内容
    content = MIMEText(send_str, _subtype='html', _charset='utf8')
    msg.attach(content)
    
    # 构建并添加图像对象
    img1 = MIMEImage(open(pic_path, 'rb').read(), _subtype='octet-stream')
    img1.add_header('Content-ID', 'image1')
    msg.attach(img1)

    # 邮件主题
    msg['Subject'] = '这是一封带图邮件'
    
    # 邮件收、发件人
    user = "[email protected]"
    to_list = ["[email protected]", "[email protected]"]
    msg['To'] = ';'.join(to_list)
    msg['From'] = user

    # 构建并添加附件对象
    # 如果不想直接在邮件中展示图片,可以以附件形式添加
    img = MIMEImage(open(pic_path, 'rb').read(), _subtype='octet-stream')
    img.add_header('Content-Disposition', 'attachment', filename=pic_path)
    msg.attach(img)

    # 密码(有些邮件服务商在三方登录时需要使用授权码而非密码,比如网易和QQ邮箱)
    passwd = "你的授权码"
    
    # 登录邮箱
    server = smtplib.SMTP_SSL("smtp.qq.com",port=465)
    server.login(user, passwd)
    print('Login Successful!')
    
    # 发送邮件
    server.sendmail(user, to_list, msg.as_string())
    print('Send Successful')

看,图片对象、附件对象、两个收件人,都按照我们的预期实现了!

猜你喜欢

转载自blog.csdn.net/qixizhuang/article/details/84657707
今日推荐