• 随笔: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 '发送成功'
    
    
  • 相关阅读:
    各种排序算法时间复杂度和空间复杂度表
    where 1=1和 0=1 的作用
    scala map操作 简单总结
    Scala详解---------数组、元组、映射
    Scala之String
    scala object 转Class Scala强制 类型转换
    Scala中的None,Nothing,Null,Nil
    mysql如何更新一个表中的某个字段值等于另一个表的某个字段值
    java.lang.String cannot be cast to scala.runtime.Nothing Scala中的Nothing类型
    mybatis 于 hibernate区别
  • 原文地址:https://www.cnblogs.com/caodingzheng/p/14007070.html
Copyright © 2020-2023  润新知