How to fix "search in state AUTH" errror

16 Views Asked by At

As you can see the mail.select() method is after connecting and before search, but keep getting this error(I'm using VS Code): raise self.error("command %s illegal in state %s, " imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

This is my code:

import imaplib
import email

def delete_messages_with_phrase(folder, phrase):
    # Selecting the email folder (inbox or trash)
    mail.select(folder)

    status, response = mail.search(None, 'ALL')
    email_ids = response[0].split()
    ...
  

def delete_trash_messages(delete_option, phrase=None):
    mail.select('[Gmail]/Trash')
    ...


username = '[email protected]'
password = 'password'


mail = imaplib.IMAP4_SSL('imap.gmail.com')


mail.login(username, password)


folder_choice = input("Enter folder to delete messages (inbox/trash): ").lower()
if folder_choice == 'inbox':
    delete_phrase = input("Enter phrase to delete messages: ")
    delete_messages_with_phrase('inbox', delete_phrase)
elif folder_choice == 'trash':
    delete_option = input("Delete all messages or messages with given phrase? (all/phrase): ").lower()
    if delete_option == 'all':
        delete_trash_messages('all')
    elif delete_option == 'phrase':
        phrase = input("Enter phrase to delete messages: ")
        delete_trash_messages('phrase', phrase)
else:
    print("Invalid choice.")


mail.expunge()
mail.close()
mail.logout()

I read that I have to paste the mail.select() method before mail.close() and I did it, but again same error.

0

There are 0 best solutions below