Get OTP code from LiberoMail with imaplib

Viewed 145

i need help. I would like to read the OTP code in an e-mail (specifically in the 'Social' tab from LiberoMail). I found this code on the web but I can't get it to work, I get an error: otp_split = [str(i) for i in str(otp[0])] IndexError: list index out of range

Can you help me, please? This is the code:

def get_otp():
    otp = []

    # create an IMAP4 class with SSL
    imap = imaplib.IMAP4_SSL("imapmail.libero.it", 993)
    # authenticate
    imap.login(username, password)
    print('Successfully logged in')

    status, messages = imap.select("Inbox")
    # number of top emails to fetch
    N = 1
    # total number of emails
    messages = int(messages[0])

    for i in range(messages, messages - N, -1):
        # fetch the email message by ID
        res, msg = imap.fetch(str(i), "(RFC822)")
        for response in msg:
            if isinstance(response, tuple):
                # parse a bytes email into a message object
                msg = email.message_from_bytes(response[1])
                if msg.is_multipart():
                    # iterate over email parts
                    for part in msg.walk():
                        # extract content type of email
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))
                        try:
                            # get the email body
                            body = part.get_payload(decode=True).decode()
                        except:
                            pass
                        if content_type == "text/plain" and "attachment" not in content_disposition:
                            # print text/plain emails and skip attachments
                            
                            # depending on your where your OTP is in the email, you will have to modify the string split method
                            body = body.split(' is your confirmation code.')[1]
                            body = body.split('In case if you have not tried to login')[0]
                            otp.append(int(body))

    imap.close()
    imap.logout()
    return otp

# wait for OTP
time.sleep(10)

# get OTP
otp = get_otp()
otp_split = [str(i) for i in str(otp[0])]

# fills in 4 pin OTP code
for i in range(4):
    otp_elem = browser.find_element_by_xpath('//*[@id="loginForm"]/div[1]/div/div[1]/input' + str([i + 1]))
    otp_elem.send_keys(otp_split[i])

otp_login_elem = browser.find_element_by_xpath('XPath of submit button')
otp_login_elem.click()
0 Answers
Related