in issues/201/user_tool.py [0:0]
def check_for_otp(self):
# Connect to the Gmail server using IMAP
try:
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(self.original_email, self.password)
mail.select("inbox")
# Fetch all unread emails
status, messages = mail.search(None, "UNSEEN")
if status != "OK":
print("No unread emails found.")
return None
email_ids = messages[0].split()
# Start from the latest email by reversing the list
email_ids = email_ids[::-1] # Reverse order to process latest first
# Iterate over each email until OTP is found
for email_id in email_ids:
# Fetch the email by ID
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])
# Check if the To address matches the generated new email
if msg["To"] == self.new_email:
# Extract OTP from the email body
otp_code = self._extract_otp_from_email(msg)
if otp_code:
# Delete the email containing the OTP
mail.store(email_id, '+FLAGS', '\\Deleted')
mail.expunge() # Permanently removes deleted emails from the mailbox
# Logout and return OTP
mail.close()
mail.logout()
return otp_code
# Logout if OTP not found in unread emails
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