#! /usr/bin/env python
import smtplib
import pyfiglet
import pendulum
import pytz
import datetime
import getpass
import time
import imaplib
import email
import sys
import os
import progressbar
import tqdm
from tqdm import tqdm
import enlighten
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email import encoders
import validate_email
from validate_email import validate_email
import re
import colorama
from colorama import Fore, Back, Style
colorama.init()

# myFunction = Sending MAIL
# myFunction2 = Reading Mail

TGREEN =  '\033[0;32m' # Green Text
TRED =  '\033[1;31m'
TYELLOW = '\033[0;33m'


res = pyfiglet.figlet_format("My\n       Mails", font="poison")
res2 = pyfiglet.figlet_format("Send Mail",font="hollywood")
res3=pyfiglet.figlet_format("Read Mails",font="speed")

#Initialising progressbars
sendbar = tqdm(total=100000,position=0,leave=False)


print(Fore.LIGHTGREEN_EX)
utc = pytz.utc
ist = pendulum.timezone('Asia/Calcutta')
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
currentTime = datetime.datetime.now()
currentTime.hour
if currentTime.hour < 12:
    print("Good Morning")
elif 12 <= currentTime.hour < 18:
    print('Good afternoon.')
else:
    print('Good evening.')
print('')
print('Current Date Time in UTC =', datetime.datetime.now(tz=utc))
print('Current Date Time in IST =', datetime.datetime.now(ist))
print(Style.RESET_ALL)









print(TRED + res)
print('')
print('')
print('')
time.sleep(2)

print(Fore.YELLOW)
print(TYELLOW + "####################################################################")
print(TYELLOW + "########## Less Secure App Should Remain On To Use This ############")
print(TYELLOW + "####################################################################")
print(Style.RESET_ALL)
time.sleep(1)


input("Press Enter To Continue................")






class myClass:
    def myFunction(self):

        print(TYELLOW+"================================================================================")
        print("")
        print(TYELLOW + res2)
        print("")
        print(TYELLOW+"================================================================================")



        time.sleep(2)
        input("Press Enter To Continue.......")
        print(' ')
        print(' ')
        print(' ')

        print(Fore.BLUE)
        print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        print("@@@@@@@@@@@@@@@@@@@@ TIPS @@@@@@@@@@@@@@@@@@@@@@@")
        print("@@@@@@@@@@@@@ ONLY GMAIL & OUTLOOK @@@@@@@@@@@@@@")
        print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        print(Style.RESET_ALL)
        time.sleep(2)
        print(' ')
        print(' ')
        print(' ')
        input("Press Enter To Continue.....")





        try:
            print(Fore.GREEN)
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print('')
            mail_Service = input("MAIL_SERVICE: ")
            if(mail_Service.isupper() == True):
                print(Fore.RED)
                sys.exit("Letters Should Be Small")
                print(Style.RESET_ALL)
            match = re.search(r"gmail",mail_Service)
            match2 = re.search(r"outlook",mail_Service)
            match3 = re.search(r"hotmail",mail_Service)
            if match == None and match2 == None and match3 == None:
                print(Fore.RED)
                sys.exit("Service Not Avaliable")
                print(Style.RESET_ALL)
            fromaddr = input("MAIL_ID: ")
            is_valid = validate_email(fromaddr)
            if is_valid == False:
                print(Fore.RED)
                sys.exit('This is Not a mail')
                print(Style.RESET_ALL)
            Password = getpass.getpass("PASSWORD: ")
            print('')
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print(Style.RESET_ALL)
            time.sleep(2)
            print('')
            print("Fetching Details............")
            for i in progressbar.progressbar(range(100), redirect_stdout=True):
                time.sleep(0.1)
            time.sleep(1)
            print('')
            print('')
            print('')

            print(Fore.GREEN)
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print('')
            subject = input("Subject: ")
            bodyMail = input("Body: ")
            print('')
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print(Style.RESET_ALL)
            time.sleep(2)
            print('')
            print('')

            print(Fore.LIGHTBLUE_EX)
            print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
            print('______________________/\/\/\/\/\/\/_____________________________')
            print("----------------------\/\/\/\/\/\/\/----------------------------")
            print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
            print(Style.RESET_ALL)
            print('')
            contacts = []
            toSize = int(input("To How Many People You Want To Send: "))
            print("Enter Recipient Emails: ")
            print(Fore.YELLOW)
            for i in range(0,toSize):
                cont = input()
                contacts.append(cont)
            print(Style.RESET_ALL)
            mailTimes = int(input("How Many Times You Want To Send:  "))



            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = ', '.join(contacts)
            msg['Subject'] = subject
            body = bodyMail
            msg.attach(MIMEText(body, 'plain'))





            file = input("Want To Send Any Files: 1.Yes  2.No\n")
            if file == "Yes":
                fileSize=int(input("How many Files: "))
                dir_path = input("Enter Path: ")
                files = []
                print("Enter File Names: ")
                print(Fore.YELLOW)
                for i in range(0,fileSize):
                    doc = input()
                    files.append(doc)
                print(Style.RESET_ALL)

                for f in files:  # add files to the message
                    file_path = os.path.join(dir_path, f)
                    attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
                    attachment.add_header('Content-Disposition','attachment', filename=f)
                    msg.attach(attachment)
                    pass

            elif file == "No":
                pass
            print('')
            print(Fore.LIGHTBLUE_EX)
            print('')
            print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
            print('______________________/\/\/\/\/\/\/_____________________________')
            print("----------------------\/\/\/\/\/\/\/----------------------------")
            print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
            print(Style.RESET_ALL)
            time.sleep(2)
            print('')
            print('')
            print('')

            if mail_Service == "outlook" or mail_Service == "hotmail":
                s = smtplib.SMTP('smtp-mail.outlook.com', 587)
                pass
            elif mail_Service == "gmail":
                s = smtplib.SMTP('smtp.gmail.com', 587)
                pass

            s.starttls()
            s.login(fromaddr, Password)
            print('Logging in .........')
            print('')
            for k in range(100000):
                sendbar.set_description("Sending Mail....".format(k))
                sendbar.update(1)
            sendbar.close()
            time.sleep(1)
            text = msg.as_string()
            for j in range(0,mailTimes):
                s.sendmail(fromaddr, contacts, text)
            time.sleep(2)
            print("Mail Sent.............")
            time.sleep(1)
            print('')
            print('')
            print(Fore.CYAN)
            print("<<<<<<<<<<<<<<<<<<<<<<<<<<------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print("<<<<<<<<<<<<<<<<<<<<<<<<<<------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print(Style.RESET_ALL)
            print('')
            print(Fore.YELLOW)
            print("From: ",fromaddr)
            print("To: ",contacts)
            print("Subject: ",subject)
            print("Body: ", bodyMail)
            if file == "Yes":
                print("Files: ",files)
                pass
            elif file == "NO":
                pass
            print(Style.RESET_ALL)
            print('')
            print(Fore.CYAN)
            print("<<<<<<<<<<<<<<<<<<<<<<<<<<------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print("<<<<<<<<<<<<<<<<<<<<<<<<<<------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print(Style.RESET_ALL)
            s.quit()

        except Exception as e :
            print(Fore.RED)
            print('Something Went Wrong: ')
            print(e)
            print(Style.RESET_ALL)
    def myFunction2(self):

        print(TYELLOW+"================================================================================")
        print("")
        print(TYELLOW + res3)
        print("")
        print(TYELLOW+"================================================================================")
        time.sleep(2)
        input("Press Enter To Continue.......")
        print(' ')
        print(' ')
        print(' ')

        print(Fore.BLUE)
        print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        print("@@@@@@@@@@@@@@@@@@@@ Tips @@@@@@@@@@@@@@@@@@@@@@@")
        print("@@@@@@@@@ Mail Service: GMAIL/OUTLOOK @@@@@@@@@@@")
        print("@@@@@@ Type: ALL/SEEN/UNSEEN/FROM/TO PERSON @@@@@")
        print("@@@@@@@@@@ Folder: INBOX/TRASH/SENT @@@@@@@@@@@@@")
        print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        print(Style.RESET_ALL)
        time.sleep(2)
        print(' ')
        print(' ')
        print(' ')

        try:
            print(Fore.GREEN)
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print('')
            mail_Service = input("Enter Your Mail Service: ")
            if(mail_Service.isupper() == True):
                print(Fore.RED)
                sys.exit("Letters Should Be Small")
                print(Style.RESET_ALL)
            match = re.search(r"gmail",mail_Service)
            match2 = re.search(r"outlook",mail_Service)
            match3 = re.search(r"hotmail",mail_Service)
            if match == None and match2 == None and match3 == None:
                print(Fore.RED)
                #raise ValueError(mail_Service,"Service Not Avaliable ")
                sys.exit("Service Not Avaliable")
                print(Style.RESET_ALL)
            USER_MAIL = input("ENTER MAIL_ID: ")
            is_valid = validate_email(USER_MAIL)
            if is_valid == False:
                print(Fore.RED)
                sys.exit("This is Not a Mail")
                print(Style.RESET_ALL)
            USER_PASS = getpass.getpass("ENTER MAIL_PASS: ")
            print('')
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
            print(Style.RESET_ALL)
            time.sleep(2)
            print(' ')
            print(' ')
            print(' ')





            if mail_Service == "outlook" or mail_Service == "hotmail":
                mail = imaplib.IMAP4_SSL("imap.outlook.com")
                pass
            elif mail_Service == "gmail":
                mail = imaplib.IMAP4_SSL("imap.gmail.com")
                pass
            #mail = imaplib.IMAP4_SSL('imap.gmail.com')
            mail.login(USER_MAIL,USER_PASS)

            print("Logging In...........")
            time.sleep(2)
            print(Fore.GREEN)
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print('')
            Type=input("Enter Type Of Mail: ")
            Folder = input("Enter Folder Of Mail You Want to Read: ")
            n=int(input("How Many Mails You Want To See: "))
            print('')
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
            print(Style.RESET_ALL)
            time.sleep(2)
            print(' ')
            print(' ')
            print(' ')
            print('Please Wait Till Processing.......')
            for i in progressbar.progressbar(range(100), redirect_stdout=True):
                time.sleep(0.1)
            time.sleep(1)
            print(' ')
            print(' ')


            mail.select(Folder)
            type, data = mail.search(None, Type)
            mail_ids = data[0]

            id_list = mail_ids.split()
            first_email_id = int(id_list[0])
            latest_email_id = int(id_list[-1])


            for i in range(latest_email_id,latest_email_id-n,-1):
                typ, data = mail.fetch(str(i), '(RFC822)' )

                for response_part in data:
                    if isinstance(response_part, tuple):
                        msg = email.message_from_string(str(response_part[1].decode("utf-8")))
                        email_subject = msg['subject']
                        email_from = msg['from']
                        email_to = msg['To']
                        email_date = msg['Date']
                        email_from = email_from.replace('<',' ')
                        email_from = email_from.replace('>',' ')


                        print("***********************************************************")
                        print("***********************************************************")
                        print('')
                        print(Fore.YELLOW)
                        print ('From : ' , email_from , '\n')
                        print('To :', email_to, '\n')
                        print('Date : ', email_date, '\n')
                        print ('Subject : ' , email_subject , '\n')
                        print(Style.RESET_ALL)
                        print('')
                        print("***********************************************************")
                        print("***********************************************************")
                        time.sleep(5)

        except Exception as e:
            print(Fore.RED)
            print("Something Went Wrong",e)
            print(Style.RESET_ALL)




cls1 = myClass()


try:
    print(Fore.LIGHTGREEN_EX)
    askUser = input("What You Want To Do :  ")
    print(Style.RESET_ALL)

    if askUser == "send":
        cls1.myFunction()
    elif askUser == "read":
        cls1.myFunction2()
except Exception as e:
    print(Fore.RED)
    print("Something Went Wrong")
    print(e)
    print(Style.RESET_ALL)
