import email
import pathlib
import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from nntplib import decode_header
from imapclient import IMAPClient

import email.parser

import boto3
import time
import chardet
import sys
import importlib

importlib.reload(sys)
import os


class NeteaseMail:
    # aws 账号登录
    def aws_login(self):
        client = boto3.client(service_name='comprehend', region_name='us-east-1',
                              aws_access_key_id='AKIA2E67UIMD45Y3HL53',
                              aws_secret_access_key='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')
        return client

    def aws_arn(self):
        document_classifier = 'arn:aws:comprehend:us-east-1:697864307463:document-classifier/'
        endpoint = 'arn:aws:comprehend:us-east-1:697864307463:document-classifier-endpoint/'
        return document_classifier, endpoint

    def s3_login(self):
        client = boto3.client(service_name='s3', region_name='us-east-1',
                              aws_access_key_id='AKIA2E67UIMD45Y3HL53',
                              aws_secret_access_key='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')
        return client

    # 连接邮箱服务器并登录。
    def loginEmail(self, imap_server, from_addr, password, imap_port, isssl=True):
        '''第一部分：收件IMAP4********************************************'''
        '''登录邮箱IMAP4=========================================================='''
        email_server = None
        # 993  465
        try:

            email_server = IMAPClient(imap_server, ssl=isssl, port=imap_port)
            # email_server = imaplib.IMAP4_SSL(IMAP_SERVER, 993)  # 网易企业邮箱服务器及SSL端口
            print("imap4 服务器连接成功")

            email_server.login(from_addr, password)

            email_server.id_({"name": "IMAPClient", "version": "2.1.0"})
            # email_server.login(FROM_ADDR, PASSWORD)
            print("imap4 (%s)账号密码正确，登录成功" % from_addr)
        except:
            print("imap4 服务器连接失败")
        else:
            return email_server

    # 关闭邮箱服务器连接
    def closeEmail(self, email_server):
        # 关闭select
        email_server.shutdown()
        print('退出邮箱')
        # 关闭连接
        # email_server.logout()

    # 获取邮箱内容、标题、发件人
    def getEmailContext(self, email_server):
        ''' 邮箱中收到的未读邮件的数量=========================================================='''
        # email_server.select_folder('INBOX', readonly=True) # readonly=True表明只读并不修改任何信息

        global a
        email_server.select_folder('INBOX')
        results = email_server.search('UNSEEN')  # 读取未读邮件
        print("邮箱内获取到未读邮件：", len(results))
        subject_list = []
        bodydata_list = []
        from_list = []
        uid_list = []
        email_body = []
        fujian_list = []
        image_list = []
        try:
            for uid in results:
                msgdict = email_server.fetch(uid, ['Body[]', 'ENVELOPE'], '(RFC822)')
                mailbody = msgdict[uid][b'BODY[]']
                envelope = msgdict[uid][b'ENVELOPE']
                message = email.message_from_bytes(mailbody)
                text = message.as_string()
                body = email.parser.Parser().parsestr(text)
                email_body.append(body)

                nowtime = time.asctime(time.localtime(time.time()))
                nowmonth = nowtime.split()[1]
                nowday = nowtime.split()[2]
                emailmonth = body['Date'].split()[2]
                emailday = body['Date'].split()[1]
                if emailmonth != nowmonth or emailday != nowday:
                    email_server.remove_flags(uid, b'\\Seen', silent=False)
                    continue

                subject_list.append(decode_header(body['Subject']))
                from_list.append(decode_header(body['from']))
                uid_list.append(uid)

                attlist = {}
                for part in body.walk():
                    if not part.is_multipart():
                        file = part.get_filename()  # 附件名
                        if file:
                            a = 1
                            filename = email.header.decode_header(file)[0][0]  # 附件名
                            charset = email.header.decode_header(file)[0][1]  # 编码
                            if part.get_all("Content-ID"):
                                content_id = part.get_all("Content-ID")[0][1:-1]
                            else:
                                content_id = ""  # 附件ID,也就是邮件源码里面的cid
                            ''' 多个附件时将附件名和ID对应保存到dict里面,后面将正文中的cid替换为本地保存路径 '''
                            attlist[content_id] = filename
                            ''' 附件文件名为中文或有编码的时候要进行转码 '''
                            if str(charset) != "None":
                                filename = filename.decode(charset)
                            filedata = part.get_payload(decode=True)  # 附件内容
                            ''' 把附件写到文件里面,附件一定要用wb打开,二进制 '''
                            file_path = os.path.join(os.path.dirname(__file__) + '/../emailtrainfile/image/')
                            image_list.append(file_path + filename)
                            with open(file_path + filename, "wb") as fw:
                                fw.write(filedata)
                                fw.close()

                        elif part.get_content_type() == 'text/plain':
                            con3 = part.get_payload(decode=True).strip()
                            print(chardet.detect(con3))
                            if chardet.detect(con3)['encoding'] == 'utf-8':
                                bodydata_list.append(con3.decode('utf-8'))
                            else:
                                bodydata_list.append(con3.decode('gbk'))
                if a == 1:
                    fujian_list.append('have')
                email_server.remove_flags(uid, b'\\Seen', silent=False)

        except Exception as e:
            print(e)
            print('获取内容出错')
        else:
            return subject_list, from_list, bodydata_list, uid_list, results, email_body, fujian_list, image_list
        # if subject_list and bodydata_list:
        #     data_unseen = [subject_list, bodydata_list]
        #     data_unseen1 = pd.DataFrame(data_unseen)
        #     data_unseen1.to_csv('data_unseen.csv', sep=',', header=True, index=True, encoding='utf_8_sig')
        #
        #     aws_key = "ASIA2E67UIMDTJFRF7UE"  # 【你的 aws_access_key】
        #     aws_secret = "5u6MDvm3Fabdbc6EG9+JPJE3x07peNkrvok76Dqq"  # 【你的 aws_secret_key】
        #     aws_session_token = "FwoGZXIvYXdzEHQaDKQchZxanXOpNJ2UriLoARUmKF/Uf6HZMhB4Bdo1Df4BlirgpqOyXmMULjx1yvqah1+BKIV2rzEoxxaVmvjcvLjHMQamPR7QzLZYP/WgJ6biPTnfqJWy5rCVpIZtD3D2nmGWAf5RSedADILJgBQmrXumFX2jrnm6THbqfdyfT2eitKt5ZD82zvLOaHMWu7mzomzmye8Eimt28Dhj6jsLeZPxOhhHBLUi+gddHAMCQq8HmGbnsXN5OrOBvqreRAxdR/u6vuQHbVpV3b8V5nkAtTVhOCaGRcPETARB8F/jFuFRhW9tAjPZisP/SEa8vUDR32FoMNQeda4o5+7l/gUyKYlem5bIB96gywY6s4C8c1PAa3l09+5tdGNp5laAJf7vMUzMJckR2EgF"
        #     session = Session(aws_access_key_id=aws_key,
        #                       aws_secret_access_key=aws_secret,
        #                       aws_session_token=aws_session_token,
        #                       region_name="ap-southeast-1")  # 此处根据自己的 s3 地区位置改变
        #     s3 = session.resource("s3")
        #     client = session.client("s3")
        #     bucket = "asj-oct-ipc"  # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶，否则报错
        #     upload_data = open("./././static/log/error.log", "rb")
        #     upload_key = "86YC8Z192VB1VMKU111A/vod1/test"
        #     file_obj = s3.Bucket(bucket).put_object(Key=upload_key, Body=upload_data)

    # 发送邮箱
    def faEmail(self, email_server, message, subject, from_addr, to_addr):
        if email_server:
            print("邮件开始发送")

            message = message
            msg = MIMEText(message, 'plain', 'gbk')
            msg['Subject'] = Header(subject, 'gbk')
            msg['From'] = Header(from_addr)

        try:
            msg['To'] = Header(to_addr, 'utf-8')
            email_server.sendmail(from_addr, to_addr, msg.as_string())  # 将msg转化成string发出
            print("邮件发送成功")

        except Exception as e:
            print('Error:', e)

        email_server.quit()

    def sentemail(self, email_server, uid, message, image, subject, from_addr, to_addr, iemial, ipassword):
        host = 'smtp.163.com'
        # 设置发件服务器地址
        port = 465
        # 设置发件服务器端口号。注意，这里有SSL和非SSL两种形式，现在一般是SSL方式
        # host = 'smtp.qiye.163.com'
        # port = 994
        sender = iemial
        # 设置发件邮箱，一定要自己注册的邮箱
        pwd = ipassword
        # 设置发件邮箱的授权码密码，根据163邮箱提示，登录第三方邮件客户端需要授权码
        receiver = to_addr
        # 设置邮件接收人，可以是QQ邮箱
        body = message
        # 设置邮件正文，这里是支持HTML的
        msg = MIMEMultipart()
        # msg = MIMEText(body, 'html')
        # msg = MIMEText(body, 'plain', 'utf-8')
        msg.attach(MIMEText(body, 'plain', 'utf-8'))
        msg.attach(MIMEText(body, 'html', 'utf-8'))
        if image:
            for i in image:
                print(i.split('.')[-1])
                if i.split('.')[-1] == 'png' and 'jpeg' and 'jpg':
                    with open(i, 'rb') as f:
                        msgImage = MIMEImage(f.read())
                    # 定义图片ID
                    msgImage.add_header('Content-ID', '<image1>')
                    msg.attach(msgImage)  # 添加图片
                else:
                    part_attach1 = MIMEApplication(open(i, 'rb').read())  # 打开附件
                    # 构建邮件附件
                    part_attach1.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(i).name)  # 为附件命名
                    msg.attach(part_attach1)  # 添加附件


        # 设置正文为符合邮件格式的HTML内容
        msg['subject'] = subject
        # 设置邮件标题
        msg['from'] = Header(from_addr)
        # 设置发送人
        msg['to'] = Header(to_addr)
        # 设置接收人
        try:
            s = smtplib.SMTP_SSL(host, port)
            # 注意！如果是使用SSL端口，这里就要改为SMTP_SSL
            s.login(sender, pwd)
            # 登陆邮箱
            s.sendmail(sender, receiver, msg.as_string())
            # 发送邮件！
            print('邮件转发成功')
            email_server.set_flags(uid, b'\\Seen', silent=False)
        except smtplib.SMTPException as e:
            print(e)
            print('邮件转发失败')
            email_server.remove_flags(uid, b'\\Seen', silent=False)
