Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I delete a series of incoming emails with Python while they are coming in, rather after they have all been sent?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading