Deleting gmail emails using imaplib

39 Views Asked by At

I am trying to delete emails from gmail using imaplib. The emails to be deleted are from specific set of email ids (senders list). This is defined in a data frame "sender_email". I have written the code below, to parse through the dataframe and keep fetching email from one sender email at a time and keep appending it to mail via mail.store. Then I am permanently deleting the emails.

I have written the code below, to parse through the dataframe and keep fetching email from one sender email at a time and keep appending it to mail via mail.store. Then I am permanently deleting the emails. The code is executing without any error but emails are not getting deleted. Need help with this.

for sender_email in sender_emails:
    search_criteria = f'(FROM "{sender_email}")'
    result, email_ids = mail.search(None, search_criteria)

    # Delete emails with the specified sender email ID
    for email_id in email_ids[0].split():
        mail.store(email_id, '+FLAGS', '\\Deleted')

# Permanently delete the marked emails
mail.expunge()

# Close the connection
mail.logout()

print("Emails from specified senders have been deleted.")
0

There are 0 best solutions below