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 jul 2022 · Python Standard Library

Unlock the secrets of your code with our AI-powered Code Explainer. Take a look!

Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

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 = "youremailaddress@provider.com"
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("imap.gmail.com")
# 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 imap.gmail.com 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 imap.select("SPAM") instead
imap.select("INBOX")

So we're using selecting a mailbox using imap.select() method, I've chose 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 mails we want to delete:

# search for specific mails by sender
status, messages = imap.search(None, 'FROM "googlealerts-noreply@google.com"')

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

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

Or searching by date:

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

Or if you want to delete all emails:

# to get all mails
status, messages = imap.search(None, "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
    imap.store(mail, "+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 mails that are marked as deleted, we also close the mailbox and logout from the account:

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

Awesome, the code is complete, for testing this code, I'm gonna delete all emails came from 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
...<SNIPPED>...
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.

Conclusion

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:

Finally, if you're a beginner and want to learn Python, I suggest you take the Python For Everybody Coursera course, in which you'll learn a lot about Python. You can also check our resources and courses page to see the Python resources I recommend on various topics!

Happy Coding ♥

Loved the article? You'll love our Code Converter even more! It's your secret weapon for effortless coding. Give it a whirl!

View Full Code Generate Python 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!