in utils/email_handler.py [0:0]
def read_otp_code(self, retries=5, delay=6):
"""
Retrieves the OTP code from unread emails.
Args:
retries (int): Number of retries to attempt fetching the OTP code.
delay (int): Delay in seconds between retries.
Returns:
str: The OTP code if found, else None.
"""
logging.info("Attempting to read OTP code from emails.")
# Loop to retry fetching the OTP for a specified number of attempts
for i in range(retries):
# Search for unread emails with the subject "Expensify magic sign-in code:"
self.imap.select("inbox")
status, messages = self.imap.search(None, '(UNSEEN SUBJECT "Expensify magic sign-in code:")')
# Check if the search was successful
if not status == "OK":
logging.error(f"Failed to search for emails. Retrying {i + 1}/{retries}...")
time.sleep(delay)
continue
# If there are any matching emails, process the latest one
email_ids = messages[0].split()
if not email_ids:
logging.info(f"Failed to retrieve emails. Retrying {i + 1}/{retries}...")
time.sleep(delay)
continue
latest_email_id = email_ids[-1]
status, msg_data = self.imap.fetch(latest_email_id, "(RFC822)")
# Iterate over the message data to retrieve the email content
for response_part in msg_data:
if isinstance(response_part, tuple):
# Parse the email content
msg = email.message_from_bytes(response_part[1])
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or "utf-8")
# Extract the OTP code from the email subject
match = re.search(r"Expensify magic sign-in code: (\d+)", subject)
if match:
code = match.group(1)
return code
logging.info(f"No matching emails found. Retrying {i + 1}/{retries}...")
time.sleep(delay)
logging.warning("Max retries reached. OTP code not found.")
return None