Windows平台下基于Python的邮件发送实现(以QQ邮箱为例)

先作三点说明:

1、需要开启POP\SMTP相关服务,下图为QQ邮箱示例(设置-账户-POP/IMAP/SMTP...服务),服务开启后会给一个码,即为smtp登录密码Windows平台下基于Python的邮件发送实现(以QQ邮箱为例)

2、感觉可以用在程序跑完后进行邮件提醒

3、实现过程中参考了《Python编程第四版》(翻译的不行)、网站相关技术文章

代码部分:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

class SMTPSend:

    def __init__(self, fm = '1919@qq.com', passwd = '114514', 
        to = '1919@qq.com'):
        self.msg_from = fm              # 发件邮箱
        self.msg_passwd = passwd        # 发件邮箱的登录密码
        self.msg_to = to                # 收件邮箱

    def login(self):
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(self.msg_from, self.msg_passwd)
        return server

    # 中文检测
    def chCheck(self, name):
        for n in name:
            if u'\u4e00' <= n and n <= u'\u9fff':
                return True
        return False

    # 附件构造
    def attMake(self, file):
        att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
        att['Content-Type'] = 'application/octet-stream'
        if self.chCheck(file):
            att.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', file))
        else:
            att['Content-Disposition'] = 'attachment;filename={}'.format(file)  # 相对路径
        return att

    def send(self, content = '', sub = 'subject', files = None):
        msg = MIMEMultipart()
        msg.attach(MIMEText(content, 'plain', 'utf-8'))
        msg['Subject'] = sub            # 消息主题
        msg['From'] = self.msg_from     # 消息作者
        # 附件添加部分
        if files is None:
            pass
        elif files.__class__.__name__ in ('tuple', 'list'):
            for file in files:
                msg.attach(self.attMake(file))
        else:
            msg.attach(self.attMake(files))
        msg = msg.as_string()
        # HTML构造部分,可选择实现
        # msg.attach(MIMEText(content, 'html', 'utf-8'))
        # 登录发送
        server = self.login()
        try:
            if self.msg_to.__class__.__name__ in ('tuple', 'list'):
                for mt in self.msg_to:
                    server.sendmail(self.msg_from, mt, msg)
            else:
                server.sendmail(self.msg_from, self.msg_to, msg)
        finally:
            server.quit()

if __name__ == '__main__':
    stp = SMTPSend()
    stp.send('测试邮件附件发送', '测试', ['青年政治经济学读本.pdf', '20211214.xlsx'])

效果:

Windows平台下基于Python的邮件发送实现(以QQ邮箱为例)

 

上一篇:Day 189/200 前端Table 表头及列表内容动态生成


下一篇:之前学linux四大神器grep sed cut awk的部分笔记