Skip to content

Instantly share code, notes, and snippets.

@Disassembler0
Created May 14, 2017 13:27
Show Gist options
  • Save Disassembler0/498f51e8b32d208fe9fdd68a17713834 to your computer and use it in GitHub Desktop.
Save Disassembler0/498f51e8b32d208fe9fdd68a17713834 to your computer and use it in GitHub Desktop.
dovecot-archive.sh
#!/bin/bash
USER="[email protected]"
RETENTION=120
ARCHIVE_ROOT="Archiv"
BOXES_TO_ARCHIVE=("INBOX" "Odeslaná pošta")
# Load all existing subfolders in BOXES_TO_ARCHIVE
BOXES=()
IFS=$'\n'
for BOX in ${BOXES_TO_ARCHIVE[@]}; do
BOXES+=($(doveadm mailbox list -u ${USER} ${BOX}*))
done
# Set range for mails in the year preceding RETENTION
BEFORE=$(date -d "-${RETENTION} days" "+%Y-%m-%d")
SINCE="${BEFORE:0:4}-01-01"
# Perform for the range above as well as last 10 years
for YEAR in $(seq ${BEFORE:0:4} -1 $((${BEFORE:0:4}-10))); do
# Perform for all BOXES
for BOX in ${BOXES[@]}; do
# Check if there is anything to archive in BOX for period between BEFORE and SINCE
if [ $(doveadm search -u ${USER} MAILBOX ${BOX} SENTBEFORE ${BEFORE} SENTSINCE ${SINCE} | wc -l) -gt 0 ]; then
# Create and subscribe ARCHIVE subfolder if it doesn't exist
ARCHIVE="${ARCHIVE_ROOT}/${YEAR}/${BOX}"
doveadm mailbox status -u ${USER} messages ${ARCHIVE} >/dev/null 2>&1
if [ $? -ne 0 ]; then
doveadm mailbox create -u ${USER} ${ARCHIVE}
doveadm mailbox subscribe -u ${USER} ${ARCHIVE}
fi
# Move the mails to ARCHIVE subfolder
doveadm move -u ${USER} ${ARCHIVE} mailbox ${BOX} SENTBEFORE ${BEFORE} SENTSINCE ${SINCE}
fi
done
# Move on to previous year
BEFORE="${YEAR}-01-01"
SINCE="$((${YEAR}-1))-01-01"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment