Can I automatically clean a folder in my mailbox? Let's say I want to automatically delete messages that are older than 3 months. Does dovecot/sieve have this option?
1 Answers
Apply sieve filter to mails older than x days
To archieve this goal you can use the commands doveadm move
and sieve-filter
. You could also use doveadm expunge
but with this approac you can delete or move mails older than X days.
First move all files older than 7 days to a temporary folder, in this case it is named sieve-tmp:
doveadm move -u test1@example.com INBOX.sieve-tmp user test1@example.com mailbox INBOX BEFORE $(date -d "$now -7 days" +%Y-%m-%d)
The commands takes the following arguments:
-u test1@example.com
the source users mailbox
INBOX.sieve-tmp
the folder to copy the mails to (INBOX/tmp)
user test1@example.com
the destination users mailbox, in my case the same as the source mailbox
mailbox
a required keyword
INBOX
the source folder, in this case the INBOX
BEFORE $(date -d "$now -7 days" +%Y-%m-%d)
the search filter. This filter returns mails created before the date YYYY-MM-DD. The date command delivers the date, 7 day from now. You can replace 7 with any desired number.
Created a sieve script to apply on mails older than 7 days. I created it using roundcube and deactivated it in the interface so it does not get applied to incoming mails. I called it 7d
.
sieve-filter -e -W -C -u test1@example.com /var/mail/example.com/test1/sieve/7d.sieve INBOX.sieve-tmp
-e
enables execution mode
-W
enables write mode
-C
forece compilation. The script is compiled to a binary.
-u test1@example.com
runs the script for this user.
/var/mail/example.com/test1/sieve/7d.sieve
path to the sieve script to be executed.
INBOX.sieve-tmp
folder to execute the script on.
After this all the desired mails are processed and the rest can be moved back to the Inbox:
doveadm move -u test1@example.com INBOX user test1@example.com mailbox INBOX.sieve-tmp ALL
Final script
#!/bin/bash
doveadm move -u test1@example.com INBOX.sieve-tmp user test1@example.com mailbox INBOX BEFORE $(date -d "$now -7 days" +%Y-%m-%d)
sieve-filter -e -W -C -u test1@example.com /var/mail/example.com/test1/sieve/7d.sieve INBOX.sieve-tmp
doveadm move -u test1@example.com INBOX user test1@example.com mailbox INBOX.sieve-tmp ALL
If you want another script processing mails older than X day, just copy this block and replace the time reference.
The script can be called once a day via a cron job:
crontab -e
0 0 * * * /opt/filter-my-mails.sh

- 113
- 4
-
I have no idea why this hasnt got more upvotes - it is the perfect answer. – Paul Hedderly Feb 20 '23 at 07:12