How to Delete Emails in Python?

Posted in /  

How to Delete Emails in Python?
vinaykhatri

Vinay Khatri
Last updated on October 6, 2024

    Often we wish to delete all the unwanted emails from our email inbox. Although email providers like Gmail provide a multi-select option to delete emails in the bunch, all those features are all for common users.

    As Python developers, we should be writing a dedicated Python script that can delete the emails present in the INBOX, TRASH, DRAFT, and SENT boxes.

    In this Python tutorial, we will be going to code in Python and use its inbuilt imaplib module to delete emails from our Gmail account.

    So would you like to write some Python code that can delete emails for you with a single execution?

    Let's get started.

    How to Delete Emails in Python?

    If you directly try to access the Google account and log in with your credentials with 2 Step Verification active for your Gmail account, you would not be able to log in with Python 3 party libraries.

    So in order to log in, you either have to turn down your 2SV or create an App Password using the google Gmail API.

    Check out our How to send Gmail Email with Python? the article, where we have provided all the information about how to generate an App password with Gmail. With the help of the Generated App password, you can easily log in to your Gmail account without deactivating your 2StepVerificaiton, or reducing security.

    We have already generated the App password by the name " My App, " and we will be using its 16 characters long password as the password for our Gmail login credentials. Now let's have a look at our Gmail Inbox and decide which emails we want to delete.

    For this tutorial, we will be deleting all the messages from Kaggle that have been sent from the mail address " noreply@kaggle.com." So now, let's get started with Python code.

    Python Code to Delete Emails

    Step 1 - Importing the Libraries

    First of all, we will import the imaplib library.

    import imaplib
    
    #user credentials 
    my_email= "codehundred100@gmail.com"
    app_generated_password = "nsjsmslishsnahsy"  

    In your case, you should be using your own email address and App Generated Password.

    Note: For the ease of this Python tutorial, we have put the email address and password in the plain string format. For production development, you should always use Python Environment Variables to store and use sensitive credentials like email ID and password.

    Step 2 - Login to Gmail Server

    Now let's use the credentials and log in to the Gmail server, but before that, initialize the IMAP4 object for Gmail.

    #initialize IMAP object for Gmail
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    
    #login to gmail with credentials
    imap.login(my_email, app_generated_password)

    As for this tutorial, we are deleting our Gmail messages, and that's why we are setting the IMAP server for Gmail with "imap.gamil.com" . The Python imaplib library can also map servers for different email providers. Click here to know all the supported email servers.

    Caution: Instead of Google Gmail App Password, if you are using your original password, you will receive an error indicating credentials are incorrect, and you are forced to allow a less secure app on for your setting. But we do not recommend you deactivate 2 step verification. Instead, you can use the Google App Password API as we are using for this tutorial. Never use your real Gmail password while writing automated scripts.

    Step 3 - Select the Mailbox

    After setting the server and logging in with the credentials, let's select the mailbox from where we want to delete the emails. For this tutorial, we are deleting the emails from the inbox, so we will select INBOX. To do so, we will use the imap.select() method.

    imap.select("INBOX")

    If you wish to delete email from Trash, Spam, Important, and other labels, you can specify it, such as imap.select("Trash") and imap.select("Spam") . To know all the mailboxes provided by your email provider, use the imap.list() method.

    Step 4 - Choose the Mails to Delete

    After selecting the INBOX mailbox, select the mails you want to delete. With the help of the imap.search() method, we can select the specific emails we want to delete. For this tutorial, we are deleting the mails from Kaggle with the email address noreply@kaggle.com .

    status, messages_id_list = imap.search(None, 'FROM "noreply@kaggle.com"')

    If you wish to delete all emails, you can search all mails with the imap.search(None, "ALL") statement. Else, you can also search for the emails with specific subjects using imap.search(None, 'SUBJECT "The Subject name"') . The imap.search() method returns a tuple of status string and list of byte string representing mails IDs, separated by space. Now let's grab the messages_id_list byte string and convert it into a list of message-ids.

    #convert the string ids to list of email ids
    messages = message_id_list[0].split(b' ')

    Now we have the messages , which is a list of all the searched mail IDs. Let's iterate through all its IDs and mark them as deleted with the method.

    print("Deleting mails")
    count =1
    for mail in messages:
        # mark the mail as deleted
        imap.store(mail, "+FLAGS", "\\Deleted")
    
        print(count, "mail(s) deleted")
        count +=1
    print("All selected mails has been deleted")
    
    # delete all the selected messages 
    imap.expunge()
    # close the mailbox
    imap.close()
    
    # logout from the server
    imap.logout()

    This will set all the searched mails with the delete flag, and delete all the selected emails, and log you out from the sever.

    Putting All the Code Together and Executing It

    #python program to delete emails.
    
    import imaplib
    
    my_email = "codehundred100@gmail.com"
    app_generated_password = "nsjsmslishsnahsy"
    
    #initialize IMAP object for Gmail
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    
    #login to gmail with credentials
    imap.login(my_email, app_generated_password)
    
    imap.select("INBOX")
    
    status, message_id_list = imap.search(None, 'FROM "noreply@kaggle.com"')
    
    #convert the string ids to list of email ids
    messages = message_id_list[0].split(b' ')
    
    print("Deleting mails")
    count =1
    for mail in messages:
        # mark the mail as deleted
        imap.store(mail, "+FLAGS", "\\Deleted")
    
        print(count, "mail(s) deleted")
        count +=1
    print("All selected mails have been deleted")
    
    # delete all the selected messages 
    imap.expunge()
    # close the mailbox
    imap.close()
    
    # logout from the account
    imap.logout()

    Output

    Deleting mails
    1 mail(s) deleted
    2 mail(s) deleted
    3 mail(s) deleted
    4 mail(s) deleted
    5 mail(s) deleted
    All selected mails have been deleted

    As you can see, a total of 5 emails have been deleted. Now let's check our Gmail Inbox to verify the same.

    All five emails from Kaggle have been successfully deleted. Thus, the job is done!

    Conclusion

    In this Python tutorial, we learned how to use the Python standard imaplib library to access a Gmail account and delete specific emails. As for this tutorial, we have used Gmail, but the imaplib library allows you to access other email servers too. Thus, you can work it out to know for yourself.

    Let us know if you come across any issues while doing so in the comments below.

    Email servers like Gmail are highly secure, and that's why they do not allow any third-party package to log in to their server, but using the Gmail App Passwords or by turning on the Allow the less Secure option or Deactivating the 2Step verification, we can log in to a Gmail account with the imaplib library. But we do not recommend you deactivate 2Step Verification. Instead, leverage the Gmail App Password provided by Google, which is secure and efficient.

    People are also reading:

    Leave a Comment on this Post

    0 Comments