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 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 get_gender():
    """
    Ask for gender
    """
    speech_ui.playsound('./data/ask-gender.mp3')
    text = speech_ui.take_voice()
    if (text == "mail"):
        text = "male"
    return text
def get_password():
    """Ask for password
    """
    speech_ui.playsound('./data/ask-password.mp3')
    text = speech_ui.take_voice()
    password = text.replace(' ', '')
    while True:
        if (speech_ui.confirm(password)):
            break
        else:
            continue
    return password
def get_dest_email():
    """Ask for email
    """
    speech_ui.playsound('./data/ask-destmail.mp3')
    text = speech_ui.take_voice()
    e_mail = text.replace('at', '@').replace(' ', '').replace('dot', '.')
    while True:
        if (speech_ui.confirm(e_mail)):
            break
        else:
            continue
    return e_mail
def get_name():
    """Ask for username 
    """
    speech_ui.playsound('./data/ask-name.mp3')
    text = speech_ui.take_voice()
    name = text.replace(' ', '')
    while True:
        if (speech_ui.confirm(name)):
            break
        else:
            continue
    return name
Esempio n. 7
0
def search_file(name):
    """This method searchs a file name and returns a list of available files
    finds the exact file and returns full path
    """
    #find in current user directory
    filenames = subprocess.getoutput("find ~ -iname *%s* " % name)
    if (filenames == ""):
        #find in usb and mounted spaces
        filenames = subprocess.getoutput("find /media -iname *%s* " % name)
        if (filenames == ""):
            filenames = subprocess.getoutput("find /mnt -iname *%s* " % name)
            if (filenames == ""):
                filenames = subprocess.getoutput("find / -iname *%s* " % name)
                if (filenames == ""):
                    speech_ui.playsound('./data/ask-filename-again.mp3')
                    if (speech_ui.YesOrNo()):
                        name = speech_ui.playsound('./data/ask-file.mp3')
                        search_file(name)
                    else:
                        filename = ""
    arrays = filenames.splitlines()
    length = len(arrays)
    number = 0
    if (length > 1):
        speech_ui.speak("i found %s mathcing files" % length)
        speech_ui.playsound("./data/file-prompt.mp3")
        for i in arrays:
            filename = i
            text = "file " + number + " path is: " + filename.replace(
                '/', ', ')
            speech_ui.speak(text)
            number += 1
        speech_ui.playsound('./data/ask-number.mp3')
        num = int(speech_ui.take_voice())
        filename = arrays.__getitem__(num)
    elif (length <= 1):
        for i in arrays:
            filename = i
            speech_ui.speak("file located is :%s. Is this the correct file?" %
                            filename.replace('/', ', '))
            if not (speech_ui.YesOrNo()):
                filename = ""
    return filename
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()