
import os
from email.message import EmailMessage
from common.logger import log
import smtplib
import ssl
import zipfile
from datetime import datetime
import time


class Mail(object):
    def __init__(self):
        # 邮箱服务器
        self.mail_host = 'smtp.qq.com'
        # 邮件发送者x1
        self.mail_sender = '381713747@qq.com'
        # 发送者授权码
        self.mail_authorization = 'insqahzqxxacbjhd'
        # 邮件接受者
        self.mail_receivers = 'qinguanglei@sinopharm.com'

    def send(self):
        context = ssl.create_default_context()
        # 发送的信息实例
        message = EmailMessage()
        # 邮件主题
        subject = '自动化测试结果，自动发送，请勿回复。'
        message['subject'] = subject
        # 邮件发送者
        message['From'] = self.mail_sender
        # 邮件接受者
        message['To'] = self.mail_receivers
        # 邮件内容
        message.set_content("邮件内容")
        try:
            # 获取一个smtp对象
            smtp_obj = smtplib.SMTP_SSL(self.mail_host, 465, context=context)
            smtp_obj.login(self.mail_sender, self.mail_authorization)
            smtp_obj.send_message(message)
            smtp_obj.quit()
            log.info('邮件发送成功')
        except smtplib.SMTPException as e:
            log.error('邮件发送失败%s' % e)

    def zip_dir(self):
        # 获取当前日期时间
        current_time = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))
        # 获取压缩文件主名字,直接未压缩文件目录
        zip_main_name = ReadConfig().get('REPORT-FILE', 'REPORT_DIR')
        # 拼接压缩文件名字
        zip_name = ''.join([zip_main_name, current_time, '.zip'])
        log.info(zip_name)
        zip_obj = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
        for root, dir_names, file_names in os.walk(zip_main_name):
            fpath = root.replace(zip_main_name, '')
            for file_name in file_names:
                zip_obj.write(os.path.join(zip_name, file_name), os.path.join(fpath, file_name))
        zip_obj.close()
        log.debug('压缩成功')
