zoukankan      html  css  js  c++  java
  • 发送带附件的邮件

    #_*_coding:utf-8_*_
    
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.header import Header
    from email import encoders
    import time
    import yaml,os,base64
    
    password=""
    user='hzqt210@126.com'
    class EmailClass(object):
        def __init__(self):
            self.curDateTime = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) #当前日期时间
            self.sender = 'hzqt210@126.com'  # 从配置文件获取,发件人
            self.receivers = 'hzqt210@126.com'  # 从配置文件获取,接收人
            self.msg_title = 'Msg_Title' #从配置文件获取,邮件标题
            self.sender_server = 'smtp.126.com' #从配置文件获取,发送服务器
            self.From = '<hzqt210@126.com>'
            self.To = '<hzqt210@126.com>'
    
        '''
        配置邮件内容
        '''
        @property
        def setMailContent(self):
            print self.receivers
            msg = MIMEMultipart()
            msg['From'] = Header(self.From,'utf-8')
            msg['To'] = self.To
            msg['Subject'] = Header('%s%s'%(self.msg_title,self.curDateTime),'utf-8')
    
            #附件路径
            file_path=r'C:Usershzqt2Desktop2.html'
    
            #增加附件
            html = self.addAttach(file_path,filename='2%s.html'%self.curDateTime) #自动化测试报告附件
            msg.attach(html)
    
            return msg
    
    
        '''
        增加附件
        '''
        def addAttach(self,apath,filename='Report.html'):
            with open(apath, 'rb') as fp:
                attach = MIMEBase('application','octet-stream')
                attach.set_payload(fp.read())
                attach.add_header('Content-Disposition', 'attachment', filename=filename)
                encoders.encode_base64(attach)
                fp.close()
                return attach
    
    
        '''
        发送电子邮件
        '''
        def sendEmail(self,message):
            try:
                global password
                smtpObj = smtplib.SMTP()
                smtpObj.connect(self.sender_server,25)
                smtpObj.login(user,password)
                smtpObj.sendmail(self.sender,self.receivers , message.as_string())
                smtpObj.quit()
                print "邮件发送成功"
            except smtplib.SMTPException as ex:
                print "Error: 无法发送邮件.%s"%ex
    
        #发送调用
        @property
        def send(self):
            self.sendEmail(self.setMailContent)
    
    if __name__=="__main__":
        EmailClass().send
    

      

  • 相关阅读:
    cuda基础----流
    cuda基础---异步并行执行
    cuda基础---cuda通信机制
    cuda基础-----cuda编程模型/软件体系/存储器模型
    大顶堆 小顶堆应用----中位数查找
    Maven配置阿里云镜像
    C++中bool型变量按位取反总是为true
    区分C++的继承、覆盖、隐藏、重载
    C++Primer第5章 语句
    C++Primer第4章 表达式
  • 原文地址:https://www.cnblogs.com/slqt/p/13726909.html
Copyright © 2011-2022 走看看