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()
Exemplo n.º 3
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 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()