2 imap_restore_mail.py - Tool to inject mails via IMAP
4 Copyright (c) 2012 Intra2net AG
5 Author: Plamen Dimitrov and Thomas Jarosch
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
18 import argparse, getpass
19 from mail_iterator import MailIterator
20 from file_iterator import FileIterator
21 from warnings_handler import WarningsHandler
24 LOG_FILENAME = "imap_restore_mail.log"
25 LOG_FILE_LEVEL = logging.DEBUG
26 LOG_SHELL_LEVEL = logging.INFO
27 LOG_UNCLEAN_EXIT_LEVEL = logging.WARNING
32 # prepare configuration
33 args = configure_args()
34 warnings_handler = prepare_logger()
35 logging.info("The module restore_mail_inject.py started with user %s, destination %s and source %s.",
36 args.user, args.destination, args.source)
38 # connect to unix socket or server
39 psw = getpass.getpass()
40 session = MailIterator(args.server, args.user, psw)
41 storage = FileIterator()
43 # retrieve mailbox list if a mailbox list file is specified
44 if args.mboxlistfile != "":
45 storage.load_mailbox_list(args.mboxlistfile, args.ouser)
47 # delete olf IMAP folders if no append requested
49 session.delete_mailboxes(args.destination)
50 if args.destination == "INBOX":
51 session.clear_inbox_acls(args.user)
54 path_generator = storage.load_mails(args.source, args.destination)
55 for message, mailbox, date_modified in path_generator:
56 update_mailboxes(storage, session, args)
57 session.inject_message(message, mailbox, date_modified)
59 # last iteration for mailboxes in case root mailbox has no e-mails for injection
60 update_mailboxes(storage, session, args)
62 logging.info("Finished injecting mails. Exiting with code %s.", warnings_handler.detected_problems)
63 return int(warnings_handler.detected_problems > 0)
65 def update_mailboxes(storage, session, args):
66 """Create new mailboxes if necessary and add acls to mailboxes if necessary."""
68 # create new mailboxes if found by the file iterator
69 for new_mailbox in storage.created_mailboxes:
70 session.create_mailbox(new_mailbox)
72 # add acls after all subfolders or their acls will be derived from parent folder
73 for acl_mailbox in storage.acl_mailboxes:
74 # find folder acls record and retrieve them
75 mb_acls = storage.get_mailbox_acls(acl_mailbox, args.ouser)
76 session.add_acls(acl_mailbox, mb_acls, args.ouser, args.user)
77 storage.created_mailboxes = []
78 storage.acl_mailboxes = []
81 """Configure arguments and return them."""
84 parser = argparse.ArgumentParser(description="Tool to inject mails via IMAP.")
85 parser.add_argument('-d', '--directory', dest='source', action='store',
86 required=True, help='file directory to read mails from')
87 parser.add_argument('-s', '--server', dest='server', action='store',
88 default="localhost", help='imap server name with default localhost')
89 parser.add_argument('-u', '--username', dest='user', action='store',
90 required=True, help='user to store mails to')
91 parser.add_argument('-o', '--ouser', dest='ouser', action='store',
92 default="", help='name of the original user (=username if not specified)')
93 parser.add_argument('-f', '--foldername', dest='destination', action='store',
94 default="INBOX", help='folder to store mails to - if not specified we overwrite INBOX')
95 parser.add_argument('-m', '--mboxlistfile', dest='mboxlistfile', action='store',
96 default="", help='mboxlist file (flat file format) to read the ACLs from')
97 parser.add_argument('-a', '--append', dest='append', action='store_true',
98 default=False, help="append mails, don't delete anything")
99 args = parser.parse_args()
101 # some default post processing of arguments
102 if (args.destination != "INBOX"):
103 args.destination = "INBOX/" + args.destination
104 if (args.ouser == ""):
105 args.ouser = args.user
109 def prepare_logger():
110 """Sets up the logging functionality"""
113 with open(LOG_FILENAME, 'w'):
116 # add basic configuration
117 logging.basicConfig(filename=LOG_FILENAME,
118 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
119 level=LOG_FILE_LEVEL)
121 # add a handler for a console output
122 default_logger = logging.getLogger('')
123 console = logging.StreamHandler()
124 console.setLevel(LOG_SHELL_LEVEL)
125 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
126 console.setFormatter(formatter)
127 default_logger.addHandler(console)
129 # add a handler for warnings counting
130 warnings_handler = WarningsHandler()
131 warnings_handler.setLevel(LOG_UNCLEAN_EXIT_LEVEL)
132 default_logger.addHandler(warnings_handler)
134 return warnings_handler
136 if __name__ == "__main__":