Cyrus IMAP Mailbox Recovery

I've occasionally encountered IMAP mailboxes that were unreadable and undeletable using any mail client. In Mac OS X Mail, this usually produces an "Unable to Select" error.
Here's how to fix the server-side mailbox. At the bottom is a bonus: how to recover the locally cached .imapmbox file from Mail.
I learned how to do these steps from two web pages: Bynari Support and Code Comments.
Step 1: Backup the locally-cached mail
The file will be inside ~/Library/Mail/IMAP-email-address, with an extension ".imapmbox". Copy this file to your Desktop.
Step 2: Repairing the Cyrus folder
- Use Server Admin to stop the mail server
Change to root, and enter the directory /var/imap:
# sudo -s # cd /var/imap
backup mailboxes.db:
# cp mailboxes.db mailboxes.db-backup
- Using Workgroup Manager, set user cyrus's shell to bash
su to cyrus, and dump the database to a text file:
# su cyrus # /usr/bin/cyrus/bin/ctl_mboxlist -d > /tmp/mboxlist.txt
Edit the text file and remove the lines that contain the problem folders:
# pico /tmp/mboxlist.txt
remove mailboxes.db:
# rm mailboxes.db
rebuild mailboxes.db from the new text file:
# cat /tmp/mboxlist.txt | /usr/bin/cyrus/bin/ctl_mboxlist -u
Reconstruct all mailboxes
# /usr/bin/cyrus/bin/reconstruct -r -f user
If there are any remaining folders that print an error, they'll be listed when performing cyrus reconstruct: (ie.. user.someuser: Mailbox does not exist).
Exit back from cyrus and root
# exit # exit
- Using Workgroup Manager, set user cyrus's shell back to /usr/bin/false.
- Restart Mail using Server Admin
(Ed. note: Rather than give cyrus a shell you could just use
sudo -u cyrus to do the following steps.)
Step Three: Recovering a locally-cached imapmbox
Create a fake imap email account. Don't use a real name or password. We want the account to remain offline.
Quit Mail
In the Finder, open the directory holding the newly-created INBOX.imapmbox file (It's in ~/Library/Mail/IMAP-something/").
Move this (empty) INBOX.imapmbox to the trash.
Move the cached mail file you had copied to the Desktop to this folder. Rename the file to "INBOX.imapmbox".
Start Mail again, and click on the new account name. Your messages should reappear.
Copy the messages from this folder to another one, either IMAP or locally.
In Mail's preferences, delete the account you had created.
Make sure you keep this fake account offline, or else Mail will overwrite your cached mailbox with an empty one!
