How to Delete Emails in Python

Published on Aug. 22, 2023, 12:16 p.m.

To delete emails in Python, you can use the built-in imaplib module to connect to an email server and the IMAP protocol to manage your mailbox. Here is an example code that deletes all unread emails in a specific mailbox:

import imaplib

username = '[email protected]'
password = 'your_email_password'
host = 'imap.example.com'
mailbox = 'INBOX'

# Connect to the server
server = imaplib.IMAP4_SSL(host)
server.login(username, password)

# Select the mailbox
server.select(mailbox)

# Search for unread emails
result, data = server.search(None, 'UNSEEN')

# Iterate through each email and mark it as deleted
for num in data[0].split():
    server.store(num, '+FLAGS', '\\Deleted')

# Permanently delete all marked emails
server.expunge()

# Close connection
server.close()
server.logout()

In this code, we first define the email credentials, server address, and mailbox name. We use the imaplib.IMAP4_SSL() function to connect to the email server, and we log in using the username and password. We then use the server.select() function to select the desired mailbox (replace 'INBOX' with the name of your desired mailbox).

Next, we use the server.search() function to search for all unread emails in the selected mailbox. We then iterate through each email using a for loop and mark it as deleted using the server.store() function with the '+FLAGS' and '\\Deleted' arguments. Note that this only marks the emails as deleted, and they are not actually deleted until you call the server.expunge() function.

Finally, we call the server.expunge() function to permanently delete all marked emails, and we close the connection to the server using the server.close() and server.logout() functions.

Note that this example code is for demonstration purposes only, and you should be careful when deleting emails using Python as it can have irreversible consequences.

Tags:

related content