def fetch_verification_code_from_email()

in issues/379/user_tool.py [0:0]


def fetch_verification_code_from_email(user_email, password, retries=10, delay=10):
    """
    Fetch the OTP code from the latest email.
    """
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    imap.login(user_email, password)

    for attempt in range(retries):
        imap.select("inbox")
        status, messages = imap.search(
            None, '(UNSEEN SUBJECT "Expensify magic sign-in code")'
        )
        if status == "OK":
            email_ids = messages[0].split()

            if email_ids:

                latest_email_id = email_ids[-1]
                status, msg_data = imap.fetch(latest_email_id, "(RFC822)")

                for response_part in msg_data:
                    if isinstance(response_part, tuple):
                        msg = email.message_from_bytes(response_part[1])


                        if msg.is_multipart():
                            for part in msg.walk():
                                content_type = part.get_content_type()
                                if content_type == "text/plain":
                                    body = part.get_payload(decode=True).decode()
                                    match = re.search(r'\b\d{6}\b', body)
                                    if match:
                                        otp_code = match.group(0)
                                        imap.logout()
                                        return otp_code
                        else:

                            body = msg.get_payload(decode=True).decode()
                            match = re.search(r'\b\d{6}\b', body)
                            if match:
                                otp_code = match.group(0)
                                imap.logout()
                                return otp_code
            else:
                print("No new emails found. Retrying...")
                otp_code="123456"
                return otp_code
        else:
            print("Failed to retrieve emails. Retrying...")


        time.sleep(delay)

    imap.logout()
    raise Exception("Max retries reached. No magic code email found.")