A couple of years back, I migrated all of my email off of my Postfix/Dovecot mail server to Google Apps. I was tired of fighting spam and dealing with the occasional outages to my server that would impact the family and friends whose email lived there.
I didn’t have a lot of accounts to migrate, and many of my users were POP3 users who downloaded everything — so there wasn’t a lot of email to move over. What there was I did manually with an IMAP capable email client and just copied folders and their contents “en masse” over to GMail.
This worked pretty well except for the fact that I’d been using Mutt, and had all my sent mail copied to a series of folders embedded under a parent “Sent” folder with the year and month in the name. So Sent/Sent-Mail-2001-05, etc. There were a ton of these folders and in GMail they show up as Labels. A very long list of labels. With no easy way to hide them all.
I dealt with a few manually, but GMail didn’t seem to have a way to do any sort of bulk actions within their UI, and recursively moving the contents of these folders into GMail’s Sent Mail folder from within Thunderbird wasn’t much easier.
Enter Python and imaplib. The following hacky and one-off script ended up doing the job for me pretty nicely:
LRP = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
m = imaplib.IMAP4_SSL('imap.gmail.com', 993)
status, mailboxes = m.list("/Sent", '*')
for mb in mailboxes:
flags, delimiter, mailbox_name = LRP.match(mb).groups()
s, d = m.select(mailbox_name)
# If we got an OK and there are > 0 messages in the folder.
if s == 'OK' and int(d) > 0:
print " Trying to move %d messages." % int(d)
typ, [response] = m.search(None, 'SEEN')
if typ != 'OK':
msg_ids = ','.join(response.split(' '))
m.copy(msg_ids, '[Gmail]/Sent Mail')
m.store(msg_ids, '+FLAGS', '\\Deleted')
if mailbox_name != '"Sent"':
if int(d) == 0:
print " No messages, deleting %s" % mailbox_name
print " Skipping Sent"
if __name__ == '__main__':
Now my GMail is much more neat and tidy. It would be nice if imaplib had a move() call…