def gmail_send(sender, receiver, password):
    """
    Interact with gmail api to send mails
    """
    yag = yagmail.SMTP(user=sender, password=password)
    speech_ui.playsound("./data/ask-subject.mp3")
    subject = speech_ui.take_voice()
    if (subject == "null" or subject == "empty"):
        subject = ""
    speech_ui.playsound("./data/ask-contents.mp3")
    body = speech_ui.take_voice()
    while True:
        if (speech_ui.confirm(body)):
            break
        else:
            continue
    speech_ui.playsound("./data/ask-attachment.mp3")
    if (speech_ui.YesOrNo()):
        speech_ui.playsound("./data/ask-file.mp3")
        filename = speech_ui.take_voice()
        filename = file_handler.search_file(filename)
        if (filename == ""):
            speech_ui.playsound('./data/send-blank.mp3')
            if (speech_ui.YesOrNo()):
                yag.send(to=receiver, subject=subject, contents=body)
            else:
                cleanexit.quit()
        else:
            yag.send(to=receiver,
                     subject=subject,
                     contents=body,
                     attachments=filename)
    speech_ui.playsound("./data/email_sent.mp3")
def speak(txt):
    """
    This method recieves a text and turns it into audio and then plays it
    """
    try:
        audio = gTTS(text=txt, lang='en-US')
        savelocation = "./tmp/" + ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(9)
        ]) + ".mp3"
        #save audio
        audio.save(savelocation)
        playsound(savelocation)
    except:
        playsound("./data/connection-error.mp3")
        cleanexit.quit()
def connection(host, port):
    """
    This function connects to the mail service
    and returns a connection instance
    """
    try:
        mail = smtplib.SMTP(host, port)
    except gaierror:
        speech_ui.playsound('./data/connection-error.mp3')
        cleanexit.quit()
    except (ConnectionRefusedError, smtplib.SMTPConnectError) as e:
        speech_ui.playsound('./data/bug.mp3')
        if (speech_ui.YesOrNo):
            bug = e + " " + host + " " + port
            print(bug)
        cleanexit.quit()

    return mail
def main(host, port, sender_email, sender_password, reciever_email):
    try:
        mail = connection(host, port)
        #Hostname to send for this command defaults to the FQDN of the local host.
        mail.ehlo()
        #Start a secure connection
        mail.starttls()
        #attempt login
        mail.login(sender_email, sender_password)

    except smtplib.SMTPAuthenticationError:
        text = "I'm unable to login using the given credentials, Here are the credentials that am using. Email: %s . Password: %s" % (
            sender_email, sender_password)
        speech_ui.speak(text)
        speech_ui.playsound('./data/confirm-credentials.mp3')
        if (speech_ui.YesOrNo()):
            speech_ui.playsound('./data/ask-browser.mp3')
            browserapp = speech_ui.take_voice()
            lesssecureapps.browser(browserapp, sender_email, sender_password)
        else:
            cleanexit.quit()
    if (host == "gmail"):
        gmail_send(sender_email, reciever_email, sender_password)
        speech_ui.playsound("./data/email_sent.mp3")
        cleanexit.quit()

    else:
        message = compose_mail(sender_email, reciever_email)
        mail.sendmail(sender_email, reciever_email, message)
        speech_ui.playsound("./data/email_sent.mp3")
        cleanexit.quit()
def take_voice():
    """
    This method takes in voice from user microphone and decodes it and turns it to text 
    then returns the text
    """
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        playsound("./data/prompt.mp3")
        audio = r.listen(source)
    playsound("./data/interpreting.mp3")
    #Convert audio to text
    try:
        text = r.recognize_google(audio)
        if (text == "nevermind" or text == "exit"):
            cleanexit.quit()
    except sr.UnknownValueError:
        playsound("./data/didnt_understand.mp3")
        text = take_voice()
    except (sr.RequestError, http.client.RemoteDisconnected):
        playsound("./data/connection-error.mp3")
        cleanexit.quit()
    return text
def login(host, port, email, password):
    """
    Check login from user
    """
    try:
        mail = connection(host, port)
        #Hostname to send for this command defaults to the FQDN of the local host.
        mail.ehlo()
        #Start a secure connection
        mail.starttls()
        #attempt login
        mail.login(email, password)
    except smtplib.SMTPAuthenticationError:
        text = "I'm unable to login using the given credentials, Here are the credentials that am using. Email: %s . Password: %s" % (
            email, password)
        speech_ui.speak(text)
        speech_ui.playsound('./data/confirm-credentials.mp3')
        if (speech_ui.YesOrNo()):
            speech_ui.playsound('./data/ask-browser.mp3')
            browserapp = speech_ui.take_voice()
            lesssecureapps.browser(browserapp, email, password)
        else:
            cleanexit.quit()
def compose_mail(sender, reciever):
    """
    This method composes the email with acceptable standards
    and retunrns as a message string
    """
    sender_email = sender
    receiver_email = reciever
    speech_ui.playsound("./data/ask-subject.mp3")
    subject = speech_ui.take_voice()
    if (subject == "null" or subject == "empty"):
        subject = ""
    speech_ui.playsound("./data/ask-contents.mp3")
    body = speech_ui.take_voice()
    while True:
        if (speech_ui.confirm(body)):
            break
        else:
            continue
    #Ask if attachment is needed
    speech_ui.playsound("./data/ask-attachment.mp3")
    if (speech_ui.YesOrNo()):
        #Ask name of attchments
        speech_ui.playsound('./data/ask-file.mp3')
        filename = speech_ui.take_voice()
        filename = file_handler.search_file(filename)
        if (filename == ""):
            speech_ui.playsound('./data/send-blank.mp3')
            if (speech_ui.YesOrNo()):
                msg = MIMEText(body)
                msg['Subject'] = subject
                msg['From'] = sender_email
                msg['To'] = receiver_email
                text = msg.as_string()
            else:
                cleanexit.quit()
        # Create a multipart message and set headers
        message = MIMEMultipart()
        message["From"] = sender_email
        message["To"] = receiver_email
        message["Subject"] = subject
        # Add body to email
        message.attach(MIMEText(body, "plain"))
        # Open file in binary mode
        with open(filename, "rb") as attachment:
            # Add file as application/octet-stream
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment.read())
        # Encode file in ASCII characters to send by email
        encoders.encode_base64(part)
        # Add header as key/value pair to attachment part
        part.add_header(
            "Content-Disposition",
            f"attachment; filename={filename}",
        )
        # Add attachment to message and convert message to string
        message.attach(part)
        text = message.as_string()
    else:
        msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = sender_email
        msg['To'] = receiver_email
        text = msg.as_string()
    return text
def main():
    """The main controller
    """
    NotEmpty, Users = accounts.check_users_in_db()
    if (NotEmpty):
        numberofusers = len(Users)
        if (numberofusers > 1):
            speech_ui.playsound('./data/multiple-users.mp3')
            text = get_name()
            try:
                ID = accounts.get_id(text)
                username = text
                acc = accounts.get_accounts(ID)
            except (UnboundLocalError, TypeError):
                speech_ui.playsound('./data/no-user.mp3')
                cleanexit.quit()
            if (len(acc) > 1):
                try:
                    email_acc = get_email()
                    emailacc, password, host = accounts.get_logins(email_acc)
                except (TypeError, UnboundLocalError):
                    speech_ui.playsound('./data/no-email.mp3')
                    cleanexit.quit()
            else:
                if not acc:
                    speech_ui.speak(
                        "%s! You do not have an account Please add one" %
                        username)
                    newemail = get_email()
                    newhost = get_host(newemail)
                    newpassword = get_password()
                    accounts.add_account(newhost, ID, newemail, newpassword)
                    cleanexit.quit()
                else:
                    for i in acc:
                        emailacc, password, host = i
        else:
            for i in Users:
                ID, username, gender = i
            acc = accounts.get_accounts(ID)
            if (len(acc) > 1):
                try:
                    speech_ui.playsound('./data/many-emails.mp3')
                    email_acc = get_email()
                    emailacc, password, host = accounts.get_logins(email_acc)
                except (TypeError, UnboundLocalError):
                    speech_ui.playsound('./data/no-email.mp3')
                    cleanexit.quit()
            else:
                if not acc:
                    speech_ui.speak(
                        "%s! You do not have an account Please add one" %
                        username)
                    newemail = get_email()
                    newhost = get_host(newemail)
                    newpassword = get_password()
                    accounts.add_account(newhost, ID, newemail, newpassword)
                    cleanexit.quit()
                else:
                    for i in acc:
                        emailacc, password, host = i
        host = get_host(emailacc)
        imapname, imapport, smtpname, smtpport = accounts.get_host(host)
        text = """
        Welcome %s!. What would you wish to do?
        1. Check inbox.
        2. Compose email.
        3. Add an account.
        4. Delete an account.
        5. Add a new user.
        6. Delete a user.""" % username
        speech_ui.speak(text)
        text = speech_ui.take_voice()
        homophonesOne = ['one', '1', 'warn']
        homophonesTwo = ['two', '2', 'too']
        homophonesFour = ['for', '4']
        if (text in homophonesOne):
            recieve_mails.get_email(imapname, imapport, emailacc, password)
        elif (text in homophonesTwo):
            reciever = get_dest_email()
            send_mails.main(smtpname, smtpport, emailacc, password, reciever)
        elif (text == '3'):
            newemail = get_email()
            newhost = get_host(newemail)
            newpassword = get_password()
            accounts.add_account(newhost, ID, newemail, newpassword)
            cleanexit.quit()
        elif (text in homophonesFour):
            text = get_email()
            accounts.delete_account(text)
            cleanexit.quit()
        elif (text == '5'):
            name = get_name()
            gender = get_gender()
            accounts.insert_user(name, gender)
            cleanexit.quit()
        elif (text == '6'):
            name = get_name()
            accounts.delete_user(name)
            cleanexit.quit()
    else:
        initial_setup()
def get_email(host, port, email, password):
    """
    This method authenticates with imap to recieve emails
    """
    try:
        mail = imaplib.IMAP4_SSL(host, port)
    except:
        try:
            mail = imaplib.IMAP4_SSL(host, port)
        except:
            speech_ui.playsound("./data/connection-error.mp3")
            cleanexit.quit()

    try:
        mail.login(email, password)
    except:
        try:
            mail.login(email, password)
        except:
            text = "I'm unable to login using the given credentials, Here are the credentials that am using. Email: %s . Password: %s" % (
                email, password)
            speech_ui.speak(text)
            speech_ui.playsound('./data/confirm-credentials.mp3')
            if (speech_ui.YesOrNo()):
                speech_ui.playsound('./data/ask-browser.mp3')
                browserapp = speech_ui.take_voice()
                lesssecureapps.browser(browserapp, email, password)
        else:
            cleanexit.quit()

    status, totalmail = mail.select(mailbox='inbox')
    del status
    text = "You have A Total of %s, emails in your, inbox. Please wait as I search for unread emails" % str(
        totalmail).replace('b', '')
    speech_ui.speak(text)
    status, data = mail.uid('search', None, "(UNSEEN)")
    inbox_item_list = data[0].split()
    try:
        new = int(inbox_item_list[-1])
        old = int(inbox_item_list[0])
    except IndexError:
        text = "You have 0, unread emails . I am logging out . !Bye"
        speech_ui.speak(text)
        mail.close()
        mail.logout()
        cleanexit.quit()

    for i in range(new, old - 1, -1):
        status, email_data = mail.uid('fetch', str(i).encode(), '(RFC822)')
        raw_email = email_data[0][1].decode("utf-8")
        email_message = mal.message_from_string(raw_email)
        From = email_message['From']
        Subject = str(email_message['Subject'])
        if (Subject == ""):
            Subject = "empty"
        text = "You have a message from: %s . The subject Of the Email is: %s" % (
            From, Subject)
        speech_ui.speak(text)
        mail_message = get_first_text_block(email_message)
        usehtml = "use a HTML compatible email viewer"
        if (mail_message.__contains__(usehtml)):
            for part in email_message.get_payload():
                if part.get_content_maintype() == 'text':
                    body = part.get_payload()
                    soup = BeautifulSoup(body, "html.parser")
                    txt = soup.get_text()
                    txt = txt.replace(
                        "To view the message, please use a HTML compatible email viewer!",
                        '')
                    speech_ui.speak("The Body is: %s" % txt)
                    status, data = mail.store(
                        str(i).encode(), '+FLAGS', '\\Seen')
                    speech_ui.playsound('./data/ask-reply.mp3')
                    if (speech_ui.YesOrNo()):
                        send_mails.main(host, port, email, password, From)
                    cleanexit.quit()
        else:
            text = mail_message
            speech_ui.speak("The Body is: %s" % text)
            speech_ui.playsound('./data/ask-reply.mp3')
            if (speech_ui.YesOrNo()):
                send_mails.main(host, port, email, password, From)
            status, data = mail.store(str(i).encode(), '+FLAGS', '\\Seen')
            cleanexit.quit()