导航

 
#_*_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:\Users\hzqt2\Desktop\2.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

  

posted on 2020-09-24 21:52  slqt  阅读(303)  评论(0编辑  收藏  举报