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 = "[email protected]" 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")
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 "[email protected]"')
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.
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.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) # decode the email subject subject = decode_header(msg["Subject"]) 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:
And 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 a 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 ♥View Full Code