imaplib.error: command SEARCH illegal in state AUTH

imaplib.error: command SEARCH illegal in state AUTH

我正在尝试编写将进入我的收件箱并自动删除某些我不再需要的电子邮件的代码。我实际上是从网站上复制并粘贴它的,但是无论我如何尝试和调整它,当我 运行 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

代码在这里:

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()
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()