I am writing a program to spam an email inbox with a large amount of emails at once. I am attempting to create a filter in order to delete these emails. I have the following code so far but only works until after all the emails have been sent and doesnt delete them while they are being delivered. (This code is from https://www.thepythoncode.com/article/deleting-emails-in-python I am simply trying to add onto it)
import imaplib
import email
from email.header import decode_header
username = "testproject400@outlook.com"
password = "blank for a reason"
imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
imap.login(username, password)
imap.select("INBOX")
status, messages = imap.search(None, 'FROM "blank for a reason"')
messages = messages[0].split(b' ')
for mail in messages:
msg = imap.fetch(mail, "(RFC822)")
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
subject = decode_header(msg["Subject"])[0][0]
if isinstance(subject, bytes):
subject = subject.decode()
print("Deleting", subject)
imap.store(mail, "+FLAGS", "\\Deleted")
imap.expunge()
imap.close()
>Solution :
That’s impossible. You can’t delete something from an inbox that is not in that inbox yet.
If you want to reject emails rather than receive them, you would have to write a filter for your inbound SMTP server (who seems not to be run by you, so you can’t), and even then this principle wouldn’t logically work – you must have received the email at least partially to be able to check it.
So this all falls flat on the logic/causality aspect of your problem.