Search code examples
pythonimaplib

imaplib.error: command SEARCH illegal in state AUTH


I'm trying to write code that will go into my inbox and delete certain emails that I don't want any more automatically. I practically copied and pasted it from a website, but no matter how I try and tweak it I get this same error when I run it:

Traceback (most recent call last):
  File "c:\Users\Butler\OneDrive\Documents\Code\Email_Deleting_Bot.py", line 12, in <module>
    status, messages = imap.search (None, 'ALL')
  File "C:\Users\Butler\AppData\Local\Programs\Python\Python39\lib\imaplib.py", line 734, in search
    typ, dat = self._simple_command(name, *criteria)
  File "C:\Users\Butler\AppData\Local\Programs\Python\Python39\lib\imaplib.py", line 1230, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\Butler\AppData\Local\Programs\Python\Python39\lib\imaplib.py", line 968, in _command
    raise self.error("command %s illegal in state %s, "
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

The code is here:

import imaplib
import email
from email.header import decode_header

username = ''
password = ''

imap = imaplib.IMAP4_SSL ('imap.gmail.com')
imap.login (username, password)

imap.select ('DRAFTS')
status, messages = imap.search (None, 'ALL')
messages = messages [0].split(b' ')

for mail in messages:
    _, msg = imap.fetch(mail, "(RFC822)")

imap.expunge()
imap.close()
imap.logout()

Solution

  • import imaplib
    import email
    from email.header import decode_header
    
    username = ''
    password = ''
    
    imap = imaplib.IMAP4_SSL ('imap.gmail.com',993)
    imap.login (username, password)
    
    print(imap.list())
    imap.select('[Gmail]/Drafts')
    
    status, messages = imap.search (None, 'ALL')
    messages = messages [0].split(b' ')
    
    for mail in messages:
        _, msg = imap.fetch(mail, "(RFC822)")
    
    imap.expunge()
    imap.close()
    imap.logout()