Automating IMAP to mbox Conversion for Mass Email Export

As an administrator, I’ve faced a situation where I needed to export emails from a large number of accounts on a Surgemail server. The problem was that the domain had been changed to a new administration, and before deleting the old account, they requested me to convert their emails to mbox format for archival purposes.

The catch was that there were over 200 mailboxes to convert, which made it impractical to do manually. I needed to find an automated solution to streamline the process.

After searching online, I discovered a Python script called imapbackup.py that could perform the IMAP to mbox conversion. However, the script required me to create another script to generate a list of email addresses from the Surgemail server.

I used the ListAllMails.sh script (available on Surgemail’s website) to extract only the emails from a specific domain into a text file. This file became my list of email addresses.

To create this file, I ran the following command:

ListAllMails.sh | grep [DOMAIN_PRETENDIDO] > [FICHEIRO_DE_OUTPUT]

This command generated a file called exportemails.txt with only the emails from the specified domain. The script then used this file as input for the IMAP backup process.

Now that I had my list of email addresses, I needed to modify the Python script (imapbackup.py) to work with the Surgemail server and the mbox format. After some adjustments, I created a new script called export_emails.sh:

#!/bin/bash

listemail=/tmp/exportemails.txt
outputdir=/tmp/mails
imapbackup=/tmp/imapbackup.py
serverip=192.168.1.4

cat $listemail | while read line
do
  cd $outputdir
  echo "$line"
  tellmail change_pass "$line" password
  mkdir $outputdir/"$line"
  cd $outputdir/"$line"
  python $imapbackup -s $serverip -u "$line" -p password
done

This script loops through each email address in the exportemails.txt file, creates a new directory for each account, changes the password (since we don’t know the original passwords), and then runs the IMAP backup script to convert the emails to mbox format.

Please note that this script will alter the passwords of all users whose accounts are being exported. This is because we cannot access the IMAP server without knowing the original passwords. However, since these accounts will no longer be needed on the Surgemail server, it’s acceptable to change their passwords for archival purposes only.

To use the imapbackup.py script with mbox format, you can add the -z option after running the Python script:

python $imapbackup -s $serverip -u "$line" -p password -z

However, keep in mind that this will result in compressed mbox files which need to be decompressed before use.

I hope this tutorial helps anyone looking for a way to automate IMAP to mbox conversions on the Surgemail server.