How to Delete Emails in Python

Learn how you can use IMAP protocol to delete specific mails in your email account in a selected mailbox using the built-in imaplib module in Python.
  · 5 min read · Updated may 2024 · Python Standard Library

Welcome! Meet our Python Code Assistant, your new coding buddy. Why wait? Start exploring now!

Have you ever wanted to delete emails in your mail box but you know it'll take a lot of your time and effort to do it manually ?

In this tutorial, you will not only learn how to delete emails automatically using Python, but you'll also learn how to filter emails by date, subject, sender and more, in order to delete them in one shot.

We gonna be using the Python built-in's imaplib module, but if you want to use some sort of API, we have a tutorial on how to use Gmail API where we show how to read, send and delete emails in Python. 

imaplib implements IMAP protocol in Python, IMAP is an Internet standard protocol used by email clients to retrieve and also delete email messages from a mail server.

Let's start by importing the necessary modules and specifiying our account credentials:

import imaplib
import email
from email.header import decode_header

# account credentials
username = ""
password = "yourpassword"

You should put your account credentials of course. The below code is responsible for connecting to the IMAP server of the mail provider:

# create an IMAP4 class with SSL 
imap = imaplib.IMAP4_SSL("")
# authenticate
imap.login(username, password)

For the demonstration of this tutorial, I'm using a demo Gmail account, so that's the reason I'm specifying server. For other providers, check this link that contains list of IMAP servers for most commonly used email providers.

Also, if you're using a Gmail account and the above code raises an error indicating that the credentials are incorrect, make sure you allow less secure apps on your account settings.

Now that we've logged in to our mail account, let's select our targeted mailbox:

# select the mailbox I want to delete in
# if you want SPAM, use"SPAM") instead"INBOX")

So we're selecting a mailbox using method, I've chosen INBOX folder for this tutorial, you can print imap.list() for available mailboxes in your account.

Now let's make an IMAP search to search for emails we want to delete:

# search for specific mails by sender
status, messages =, 'FROM ""')

The above line searches for emails that were sent from Google Alerts email, another example may be searching by SUBJECT:

# to get mails by subject
status, messages =, 'SUBJECT "Thanks for Subscribing to our Newsletter !"')

Or searching by date:

# to get mails after a specific date
status, messages =, 'SINCE "01-JAN-2020"')
# to get mails before a specific date
status, messages =, 'BEFORE "01-JAN-2020"')

Or if you want to delete all emails:

# to get all mails
status, messages =, "ALL")

I gave you a lot of choices, you should only select one search line depending on your use case. For a list of IMAP search criteria, check this link.

The status contains a string whether the search was successfully executed, messages is returned as a list of a single byte string of mail IDs separated by a space, let's convert it to a list of integers:

# convert messages to a list of email IDs
messages = messages[0].split(b' ')

Now let's iterate over targeted mails and mark them as deleted:

for mail in messages:
    _, msg = imap.fetch(mail, "(RFC822)")
    # you can delete the for loop for performance if you have a long list of emails
    # because it is only for printing the SUBJECT of target email to delete
    for response in msg:
        if isinstance(response, tuple):
            msg = email.message_from_bytes(response[1])
            # decode the email subject
            subject = decode_header(msg["Subject"])[0][0]
            if isinstance(subject, bytes):
                # if it's a bytes type, decode to str
                subject = subject.decode()
            print("Deleting", subject)
    # mark the mail as deleted, "+FLAGS", "\\Deleted")

As said in the comments above, you can delete the inside for loop if you want performance, I grabbed it from reading emails tutorial, it is there only for printing the SUBJECT of the email, so we know what we're deleting.

Finally, we execute the imap.expunge() method that permanently removes emails that are marked as deleted, we also close the mailbox and log out from the account:

# permanently remove mails that are marked as deleted
# from the selected mailbox (in this case, INBOX)
# close the mailbox
# logout from the account

Awesome, the code is complete, for testing this code, I'm gonna delete all emails that came from the Google Alerts email:

Emails to DeleteAnd indeed, after I ran the script, I got this output:

Deleting Alerte Google – Bitcoin
Deleting Alerte Google – Bitcoin
Deleting Alerte Google – Bitcoin
Deleting Alerte Google – Bitcoin

For this demo, all the emails have the same title, as I filtered it by the sender email, but if you run different search criteria, you'll see different output of course.


Great, now you have the skills to automatically delete emails using imaplib module in Python.

I suggest you create a new email account and test this code on it, as you can make irreversible mistakes on your main email accounts.

Check the full code here.

Here are other Python email tutorials:

Happy Coding ♥

Want to code smarter? Our Python Code Assistant is waiting to help you. Try it now!

View Full Code Transform My Code
Sharing is caring!

Read Also

Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!