随笔:Python发送SMTP邮件方法封装

随笔:Python发送SMTP邮件方法封装

1、封装的方法可以用来发送附件
2、附件名称为中文不会乱码
3、也可以不带附件
4、正文是纯文本

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr


class Send_smtp_email_report(object):
    '''
    这是用来发送SMTP协议的报告邮件
    '''
    def __init__(self, sender, password, name=''):
        '''
        :param sender: 发送邮件人的邮箱
        :param password: 发送邮件人的密码
        :param name: 发送邮件人的姓名
        '''
        self.__name = name
        self.__sender = sender
        self.__password = password

    def send_smtp_email_report(self, receive, subject, send_report, text='', smtp_server='smtp.qq.com', name='', report_name=''):
        '''
        :param receive: 收件人的邮箱
        :param subject: 邮件主题
        :param send_report: 附件报告的绝对路径
        :param report_name: 附件名称
        :param text: 邮件正文
        :param smtp_server:SMTP服务器,如'smtp.qq.com',默认是smtp_server='smtp.qq.com'
        :param name:收件人名称
        :return:
        '''
        # 设置邮件
        msg = MIMEMultipart()
        msg['From'] = formataddr((Header(self.__name, 'utf-8').encode(), self.__sender))
        msg['To'] = formataddr((Header(name, 'utf-8').encode(), receive))
        msg['Subject'] = Header(subject, 'utf-8').encode()

        # 邮件正文
        txt = MIMEText(text)

        # 将正文加载到邮件中
        msg.attach(txt)
        try:
            # 构造附件
            file = open(send_report, 'rb')
            send_file = file.read()
            file.close()

            # 设置附件
            att = MIMEText(send_file, 'base64', 'utf-8')  
            att["Content-Type"] = 'application/octet-stream'  
            att["Content-Disposition"] = 'attachment; filename="%s.html"' % (Header(report_name, 'utf-8').encode())  

            # 将附件加载到邮件中
            msg.attach(att)
        finally:
            # 发送邮件
            server = smtplib.SMTP(smtp_server, 25)
            server.set_debuglevel(1)
            server.login(self.__sender, self.__password)
            server.sendmail(self.__sender, [receive], msg.as_string())
            server.quit()
            return '发送成功'

posted @ 2020-10-22 14:28  caodingzheng  阅读(13)  评论(0编辑  收藏  举报