Python IMAP Email cleaner – automatic delete old messages

I don’t keep a secret, also I work as a system administrator in an enterprise. I have a corporate mail server with 100+ users. The problem of spam and inbox cleaning has become significant – I couldn’t get users to understand about the need to clean up mailboxes on their own. And I decided to automate this process.
The task is as follows: I need to delete all messages from the spam, junk, trash folders that are older than 30 days. My lead insisted on this time period, although I would give no more than 3 days.

MAIL_SERVER = 'mail.server.com' #mail server hostname or IP
MAX_DAYS = 30 #If your message older than 30 days it will be deleted
import csv
import imaplib
import datetime

accounts = {}
with open('accounts.csv') as f:
    accounts = dict(filter(None, csv.reader(f, delimiter=';'))) 
print(accounts)
today = datetime.date.today()
print(today)
cutoff_date = today - datetime.timedelta(days=MAX_DAYS)
before_date = cutoff_date.strftime('%d-%b-%Y')
search_args = '(BEFORE "%s")' % before_date

#Main CLEANER function
def cleanbox(mailbox, username, pasword):
    try:
        print(f'{username} with PASS {pasword}')
        imap = imaplib.IMAP4(MAIL_SERVER)
        imap.login(username, pasword)
        imap.select(mailbox)
        typ, data = imap.search(None, 'ALL', search_args)
        for num in data[0].split():
            imap.store(num, '+FLAGS', '\\Deleted')
        imap.expunge()
        imap.close()
        imap.logout()
        print(f"{mailbox} for {username} Done!")
    except:
        print(f"There is no {mailbox} folder for {username}?")

#Now just call cleaner function for your mailboxes for every users from CSV file:

for user, pas in accounts.items():
    cleanbox(mailbox='Junk', username=user, pasword=pas)

for user, pas in accounts.items():
    cleanbox(mailbox='Spam', username=user, pasword=pas)

for user, pas in accounts.items():
    cleanbox(mailbox='Trash', username=user, pasword=pas)

You need create CSV file with users credentials with “;” delimiters:

[email protected];4v4vi[j4pvoj4]v
[email protected];4rv4vioj4v
[email protected];rv4rnin49v
[email protected];rinruv9ijrf9
[email protected];ru9bv4uvbr

On my server, I got almost 3 GB of free disk space. This script can be installed in the cron scheduler to run automatically.

See also  How to create telegram bot with Aiogram and Finite State Machine

In the future, I plan to develop a convenient WEB interface using Django.

Link to this pet-project on my Github:github.com/trianid/mailcleaner

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *