# coding=utf-8
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.encoders import encode_base64
import traceback
import os, random, sys, requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

# https://blog.csdn.net/chuxu8314/article/details/100618710
# https://blog.csdn.net/Angry_Mills/article/details/79067270


class EmailUtil(object):
    host_server = 'smtp.exmail.qq.com'
    sender_email = 'data_service@elab-plus.com'
    pwd = 'elab@123A'
    send_name = 'elab'
    receiver = ['1285211525@qq.com', 'lijm@elab-plus.com', 'xuanxc@elab-plus.com']

    # 线上
    url_online = "http://dm-api.elab-plus.cn/elab-marketing-sms//mail/sendEmailForReport"

    # 开发环境
    url_dev = "http://43.254.221.77:5555/elab-marketing-sms//mail/sendEmailForReport"  # 接口地址

    # 测试环境
    url_test = "http://gatewaytest.elab-plus.com/elab-marketing-sms//mail/sendEmailForReport"

    url = url_dev

    # 消息头数据
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
        'Referer': url,
    }

    def __init__(self):
        pass

    def send_mail(self,
                  mail_title,
                  content,
                  receivers,
                  mail_excel
                  ):
        try:
            smtp = SMTP(self.host_server, 25)
            smtp.set_debuglevel(1)
            smtp.ehlo(self.host_server)
            smtp.login(self.sender_email, self.pwd)
            msg = MIMEMultipart('related')
            msg['From'] = self.send_name
            msg['Subject'] = Header(mail_title, 'gbk')
            msgAlternative = MIMEMultipart('alternative')
            msg.attach(msgAlternative)
            if content:
                textApart = MIMEText(content)
                msg.attach(textApart)
            if mail_excel:
                part = MIMEBase('application', "vnd.ms-excel")
                with open(mail_excel, 'rb') as fp:
                    part.set_payload(fp.read())
                    encode_base64(part)
                    print(os.path.split(mail_excel)[1])
                    part.add_header('Content-Disposition', 'attachment', filename=('gbk', '', os.path.split(mail_excel)[1]))
                    msg.attach(part)
            for receiver in receivers:
                msg['To'] = receiver
                try:
                    smtp.sendmail(self.sender_email, receiver, msg.as_string())
                except Exception as e:
                    print(str(e))
                    smtp.sendmail(self.sender_email, receiver, msg.as_string())
                print('Success!')
        except Exception as e:
            print('Error:{}'.format(str(e)))
            traceback.print_exc()

    def send_mail_by_admin(self,
                            mail_title,
                            content,
                            receiver,
                            mail_excel,
                            file_name,
                            url,
                            header
                           ):

        with open(mail_excel, 'rb') as f:
            m = MultipartEncoder(
                fields={
                    "enclosure": ('file', f, 'application/octet-stream'),
                    "mailAddressee": receiver,
                    "mailContent": content,
                    "mailEnclosureName": file_name,
                    "mailTitle": mail_title,
                    "mailType": "text/html",
                    "time": ""
                }
            )
            header['Content-Type'] = m.content_type
            r = requests.post(url, data=m, verify=False, headers=header)
            if r and r.json()['success']:
                return True

    def send_test(self):
        send_email = EmailUtil()
        send_email.send_mail('elab_test', '11', ['1285211525@qq.com'],
                             mail_excel=r'D:\elab-code\elab_mvp\resources\行为与模块分值汇总.xlsx')


if __name__ == '__main__':
    send_email = EmailUtil()
    result = send_email.send_mail_by_admin('移动案场订阅日报', '的数据报告已经准备完成', '15773153135@163.com', r'D:\elab-code\elab_mvp\resources\module.xlsx', 'module.xlsx')
    print(result)
