Created
December 3, 2014 19:47
-
-
Save DamianZaremba/50b9eb49b8ef1c2f8d9e to your computer and use it in GitHub Desktop.
Symbiosis email archiver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import os.path | |
import time | |
import shutil | |
import glob | |
import email | |
def get_maildirs(): | |
ignored_domains = [] | |
ignored_users = {} | |
domains = [] | |
for mbox in glob.glob('/srv/*/mailboxes/*/Maildir'): | |
parts = mbox.split('/') | |
# Ignored domains | |
if parts[2] in ignored_domains: | |
continue | |
# Ignored users | |
if parts[2] in ignored_users.keys() and \ | |
parts[4] in ignored_users[parts[2]]: | |
continue | |
domains.append(mbox) | |
return domains | |
def archive_emails(mbox): | |
if not os.path.isdir(mbox): | |
return False | |
archive_limit = 31536000 # 365 days | |
for root, dirs, files in os.walk(mbox, topdown=False): | |
for f in files: | |
path = os.path.join(root, f) | |
try: | |
fh = open(path, 'r') | |
mail = email.message_from_file(fh) | |
date = email.utils.parsedate(mail['date']) | |
if not date: | |
continue | |
year = time.strftime("%Y", date) | |
ctime = time.mktime(date) | |
except: | |
continue | |
if (time.time() - ctime) > archive_limit: | |
parts = path.split('/') | |
msg_file = parts[-1] | |
folder_dir = parts[-2] | |
folder = parts[-3] | |
if folder_dir in ['tmp', 'cur', 'new']: | |
if folder.startswith('.Archives.'): | |
lf = '.'.join(folder.split('.')[3:]) | |
else: | |
if folder == 'Maildir': | |
lf = 'Inbox' | |
else: | |
lf = folder | |
archive_folder = '.Archives.%s.%s' % (year, lf.lstrip('.')) | |
dir_path = os.path.join(mbox, archive_folder, folder_dir) | |
archive_path = os.path.join(dir_path, msg_file) | |
if not os.path.isdir(dir_path): | |
os.makedirs(dir_path) | |
if path != archive_path: | |
print 'mv %s to %s' % (path, dir_path) | |
shutil.move(path, archive_path) | |
if __name__ == '__main__': | |
for mbox in get_maildirs(): | |
archive_emails(mbox) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment