import os
from email.MIMEBase import MIMEBase
from email import Encoders
import smtplib
from elan import ElanSettings
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
from elan.ElanSettings import Script_Runner_Log,Say_Log_File_Path
Say_Log_File = Say_Log_File_Path
zip_file = r"C:\Elan_Tools\ImageScripter\ProgramData\error"
send_from ="kennyshay123test@gmail.com"
send_from ="kennyshay123test@gmail.com"
send_from_password = "corebrands123"
send_to = "kennyshay123@gmail.com"
recipients = ["kennyshay123@gmail.com",
          "ben.bickell@corebrands.com",
          "anthony.nelson@nortekcontrol.com",
          "elantestertools@gmail.com",
          "ken.shay@corebrands.com"]
#recipients = ["kennyshay123@gmail.com","elantestertools@gmail.com"]







class Error_Email_Class():
        def __init__(self,SCRIPT_NAME):
            self.SCRIPT_NAME = SCRIPT_NAME
            self.compName = str(os.environ['COMPUTERNAME'])
            ########################################Settings####################################
            pass
    
        def Send(self):
            body_bottom = ''
            # body_top = The_Exception
            with open(Say_Log_File, 'r') as myfile:
                body_top_list = myfile.read().split('\n')
            # Last selection
            Last_Ten = body_top_list[-50:]
            
            last_Item = Last_Ten[-1]
            Last_Ten.pop()
            Last_Ten.append(last_Item + " <----------------------Last")
            # Revers
            Last_Ten = Last_Ten[::-1]
            body_top = ''
            x = 0
            for i in Last_Ten:
                body_top = body_top + i + ',' + '\r\n'
                x += 1
            with open(Script_Runner_Log, 'r') as myfile:
                body_log = myfile.read()
            TWO = body_log.split('_ _ _ _ _ _ _ _ _ _ ')[0]
            THREE = body_log.split('_ _ _ _ _ _ _ _ _ _ ')[1]
            print("############TWO#################")
            print(TWO)
            print("#################################")    
            print("############THREE#################")
            print(THREE)
            print("#################################")                   
                
                
            bodylogList = body_log.split('\n')
            bodylogList = bodylogList[::-1]
            bodylogList = bodylogList[:100]
            bodylogList.append('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
            body_log = "\n".join(str(x) for x in bodylogList)
            body_Text = body_top + '\n' + body_log + '\n' + body_bottom
            msg = MIMEMultipart()
            msg['From'] = send_from
            msg['To'] = ", ".join(recipients)
            msg['Date'] = " Use any date time module to insert or use email.utils formatdate"
            msg['Subject'] = 'FAIL ( ' + ElanSettings.Elan_Build + ' ) ' + self.compName + ' ' + self.SCRIPT_NAME
            # msg['Subject'] = self.compName + "-> FAIL-> " + SCRIPT_NAME
            body = str(body_Text)
            body = MIMEText(body)  # convert the body to a MIME compatible string
            msg.attach(body)  # attach it to your main message
            part = MIMEBase('application', "octet-stream")
            zip_file_with_extention = zip_file + ".zip"
            try:
                fo = open(zip_file_with_extention, "rb")
            except Exception as e:
                print("Exception 112 -> " + str(e))
                afile = open(zip_file_with_extention, 'w')
                afile.close()
                fo = open(zip_file_with_extention, "rb")
            part.set_payload(fo.read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(zip_file_with_extention))
            msg.attach(part)
            server = smtplib.SMTP("smtp.gmail.com", 587)
            # server.ehlo()
            '''
            server.starttls()
            server.login(send_from, send_from_password)
            sent = server.sendmail(send_from, recipients, msg.as_string())
            server.close()
            
            print 'Successfully Sent The Email!'
            return sent
            '''
 

 

      
if __name__ == "__main__":
    SCRIPT_NAME = "Default"
    #Send_Certified_By_Automation_Email()
    Error_Email = Error_Email_Class(SCRIPT_NAME)
    Error_Email.Send()