in issues/223/user_tool.py [0:0]
def check_for_otp(self) -> Any:
try:
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(self.original_email, self.password)
mail.select("inbox")
status, messages = mail.search(None, "UNSEEN")
if status != "OK":
print("No unread emails found.")
return None
email_ids = messages[0].split()
email_ids = email_ids[::-1] # Reverse order to process latest first
for email_id in email_ids:
status, msg_data = mail.fetch(email_id, '(RFC822)')
if status != "OK":
print("Error fetching email.")
continue
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
if msg["To"] == self.new_email:
otp_code = self._extract_otp_from_email(msg)
if otp_code:
mail.store(email_id, '+FLAGS', '\\Deleted')
mail.expunge() # Permanently removes deleted emails from the mailbox
mail.close()
mail.logout()
return otp_code
mail.close()
mail.logout()
print("No OTP found in unread emails.")
return None
except imaplib.IMAP4.error:
print("Failed to connect to Gmail. Please check your email address or password.")
return None