Want to code faster? OurPython Code Generator lets you create Python scripts with just a few clicks. Try it 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'simaplib module, but if you want to use some sort of API, we have a tutorial onhow 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 imaplibimport emailfrom email.header import decode_header# account credentialsusername = "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")# authenticateimap.login(username, password)For the demonstration of this tutorial, I'm using a demo Gmail account, so that's the reason I'm specifyingimap.gmail.com server. For other providers, checkthis 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 youallow 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") insteadimap.select("INBOX")So we're selecting a mailbox usingimap.select() method, I've chosenINBOX folder for this tutorial, you can printimap.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 senderstatus, messages = imap.search(None, 'FROM "googlealerts-noreply@google.com"')The above line searches for emails that were sent from Google Alerts email, another example may be searching bySUBJECT:
# to get mails by subjectstatus, messages = imap.search(None, 'SUBJECT "Thanks for Subscribing to our Newsletter !"')Or searching by date:
# to get mails after a specific datestatus, messages = imap.search(None, 'SINCE "01-JAN-2020"')# to get mails before a specific datestatus, messages = imap.search(None, 'BEFORE "01-JAN-2020"')Or if you want to delete all emails:
# to get all mailsstatus, 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, checkthis link.
Thestatus 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 IDsmessages = 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 fromreading emails tutorial, it is there only for printing theSUBJECT of the email, so we know what we're deleting.
Finally, we execute theimap.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)imap.expunge()# close the mailboximap.close()# logout from the accountimap.logout()Awesome, the code is complete, for testing this code, I'm gonna delete all emails that came from the Google Alerts email:
And indeed, after I ran the script, I got this output:
Deleting Alerte Google – BitcoinDeleting Alerte Google – BitcoinDeleting Alerte Google – Bitcoin...<SNIPPED>...Deleting Alerte Google – BitcoinFor 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 usingimaplib 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 thefull code here.
Here are other Python email tutorials:
Happy Coding ♥
Why juggle between languages when you can convert? Check out ourCode Converter. Try it out today!
View Full Code Transform My CodeGot a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!
