Imaplib [search, move, delete] Yahoo Mail

Want to:

  1. Search ALL folders including SPAM, for “specific_user@ANY domain”
  2. Move those emails to folder called DUMP
  3. Delete contents of DUMP

Unfortunately I can’t figure out how to do what I need above in Yahoo Mail!

My code so far below:

import imaplib
import time

####### IMAP SSL #######
start = time.time()
try:
    imap_ssl = imaplib.IMAP4_SSL(host="imap.mail.yahoo.com", port=993)
except Exception as e:
    print("ErrorType : {}, Error : {}".format(type(e).__name__, e))
    imap_ssl = None

print("Connection Object : {}".format(imap_ssl))
print("Total Time Taken  : {:,.2f} Seconds".format(time.time() - start))


####### Login to Mailbox #######
print("Logging into mailbox...")
try:
    resp_code, response = imap_ssl.login("xxxxxxxxx@yahoo.com", "xxxxxxxxxx")
except Exception as e:
    print("ErrorType : {}, Error : {}".format(type(e).__name__, e))
    resp_code, response = None, None

print("Response Code : {}".format(resp_code))
print("Response      : {}\n".format(response[0].decode()))


####### Missing code to search, move and delete #######




####### Logout of Mailbox #######
print("\nLogging Out....")
try:
    resp_code, response = imap_ssl.logout()
except Exception as e:
    print("ErrorType : {}, Error : {}".format(type(e).__name__, e))
    resp_code, response = None, None

print("Response Code : {}".format(resp_code))
print("Response      : {}".format(response[0].decode()))

Want to search folder “SPAM”, for specific_user@any domain, and delete found mail.

Code below …

import imaplib

box = imaplib.IMAP4_SSL('imap.mail.yahoo.com', 993)
box.login("xxxxxxxx@yahoo.com","xxxxxxxxxx")
box.select('SPAM')
typ, data = box.search(None, 'from','name@*.*')
for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()

… is generating these errors below, please assist in debugging, thanks.

Traceback (most recent call last):
  File "C:\Users\Desktop\Desktop\Python Spam Buster\test.py", line 6, in <module>
    typ, data = box.search(None, 'from','name@*.*')
  File "C:\Users\Desktop\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 734, in search
    typ, dat = self._simple_command(name, *criteria)
  File "C:\Users\Desktop\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 1230, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\Desktop\AppData\Local\Programs\Python\Python310\lib\imaplib.py", line 968, in _command
    raise self.error("command %s illegal in state %s, "
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.