[python 自动发邮件(QQemail) 超级详细] 支持.txt,.py,.xlsx,.csv,inner_image, .png,.jpg,文本

"""
@Create time : 2023/4/15 15:29
@Functions   :
@author      : Lx
"""
import smtplib
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
import os.path as osp
import warnings


class AutoEmail:
    """
    支持发送: txt,log,csv,xlsx,jpg,png,py,文本内容, html文本
    功能:自动根据文件后缀调用对应的处理方法;如果不是文件,则自动使用文本发送
    """

    def __init__(self,
                 host_server='smtp.qq.com',
                 sender_qq='xxx@qq.com',
                 pwd='xxx',
                 receiver='xxx@qq.com',
                 mail_title='项目运行日志'):
        self.host_server = host_server  # qq邮箱smtp服务器
        self.sender_qq = sender_qq  # 发件人邮箱
        self.pwd = pwd  # 授权码
        self.receiver = receiver  # 接受者
        self.mail_title = mail_title  # 邮件标题
        self.reset_sources()

        self.img_count = 0

    def addpng(self, file):
        # 附件图像png
        with open(file, 'rb') as f:
            attachment = MIMEImage(f.read())
        attachment.add_header('Content-ID', 'imageid')
        show_name = osp.basename(file)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=Header(show_name, 'utf-8').encode())
        self.msg.attach(attachment)

        # 将图片添加到正文
        self.addinnerimage(file)

        self.img_count += 1

    def addjpg(self, file):
        self.addpng(file)

    def addtxt(self, file):
        # 附件txt文件
        with open(file, 'rb') as f:
            attachment = MIMEText(f.read(), 'base64', 'utf-8')
        attachment["Content-Type"] = 'application/octet-stream'
        show_name = osp.basename(file)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=Header(show_name, 'utf-8').encode())
        self.msg.attach(attachment)

    def addpy(self, file):
        self.addtxt(file)

    def addcsv(self, file):
        # 附件csv
        with open(file, 'rb') as f:
            attachment = MIMEText(f.read(), 'base64', 'utf-8')
        show_name = osp.basename(file)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=Header(show_name, 'utf-8').encode())
        self.msg.attach(attachment)

    def addlog(self, file):
        # 附件log文件
        with open(file, 'rb') as f:
            attachment = MIMEText(f.read(), 'base64', 'utf-8')
        attachment["Content-Type"] = 'application/octet-stream'
        show_name = osp.basename(file)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=Header(show_name, 'utf-8').encode())
        self.msg.attach(attachment)

    def addxlsx(self, file):
        # 附件xslx
        with open(file, 'rb') as f:
            attachment = MIMEApplication(f.read())  # 文件
        show_name = osp.basename(file)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=Header(show_name, 'utf-8').encode())
        self.msg.attach(attachment)  # 添加附件到邮件

    def addcontext(self, context):
        # 普通文本内容
        self.msg.attach(MIMEText(context + '\n', 'plain', 'utf-8'))

    def addHtmlContext(self, context):
        # 带html的信息
        self.msg.attach(MIMEText(context, 'html', 'utf-8'))

    def addinnerimage(self, file, txt=''):
        txt = txt or file
        imgbody = f'''
        <h3>{txt}</h3>
        <img src="cid:image{self.img_count}"/>
        '''
        msgtext = MIMEText(imgbody, "html", "utf-8")
        self.msg.attach(msgtext)

        with open(file, "rb") as f:
            img = MIMEImage(f.read())
        img.add_header("Content-ID", f"<image{self.img_count}>")
        self.msg.attach(img)

    def reset_sources(self, srcs=[]):
        self.resource = srcs
        self.msg = MIMEMultipart()
        self.msg["Subject"] = Header(self.mail_title, 'utf-8')
        self.msg["From"] = self.sender_qq
        self.msg["To"] = Header("测试邮箱", "utf-8")

    def send(self):
        exist_files = []
        contexts = []
        for file in self.resource:
            if not osp.exists(file):
                contexts.append(file)
                print(f'({file}) 将会以文本形式添加。')
            else:
                exist_files.append(file)

        # 文本数据
        for c in contexts:
            self.addcontext(c)

        # 文件数据(附件)
        for file in exist_files:
            recall_func = getattr(self, f'add{file.split(".")[-1]}', None)
            if callable(recall_func):
                recall_func(file)
            else:
                warnings.warn(f'处理{file}文件出现问题!')

        # 发送数据
        try:
            smtp = SMTP_SSL(self.host_server)  # ssl登录连接到邮件服务器
            smtp.set_debuglevel(1)  # 0是关闭,1是开启debug
            _ = smtp.ehlo(self.host_server)  # 跟服务器打招呼,告诉它我们准备连接,最好加上这行代码
            _ = smtp.login(self.sender_qq, self.pwd)
            _ = smtp.sendmail(self.sender_qq, self.receiver, self.msg.as_string())
            _ = smtp.quit()
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("无法发送邮件")


if __name__ == '__main__':
    ae = AutoEmail()
    ae.reset_sources(['./test.csv', './test.xlsx', 'test.jpg',
                      '笔记.txt', './Records/tmp/val_results.png',
                      '测试代码', 'get_flops.py'
                      ])
    ae.send()

参考:(139条消息) Python实现自动发送邮件(详解)_msg.as_string()_小小白学计算机的博客-CSDN博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放飞自我的Coder

你的鼓励很棒棒哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值