zoukankan      html  css  js  c++  java
  • 随笔: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 '发送成功'
    
    
  • 相关阅读:
    Spring dispatcherServlet
    Tomcat tomcat-users.xml详解
    Tomcat server.xml详解
    WAR包
    Tomcat 部署
    Tomcat 使用说明
    Java sun的JDK
    Spring 使用中的设计模式
    缓存插件 EHCache 对象缓存(Spring)
    缓存插件 EHCache 页面缓存CachingFilter
  • 原文地址:https://www.cnblogs.com/caodingzheng/p/14007070.html
Copyright © 2011-2022 走看看