This is all Plamen's work, I just contributed some ideas here and there
[imap-mark-seen] / src / imap_mark_seen.py
CommitLineData
87758662 1'''
1d595a61 2imap_mark_seen.py - Tool to mark all e-mails as seen
87758662
PD
3
4Copyright (c) 2012 Intra2net AG
9bfaa115 5Author: Plamen Dimitrov
6a1e092b
PD
6
7This program is free software: you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
87758662
PD
16'''
17import logging
18import argparse, getpass
19from mail_iterator import MailIterator
20from warnings_handler import WarningsHandler
21
22# logging settings
23LOG_FILENAME = "imap_mark_seen.log"
24LOG_FILE_LEVEL = logging.DEBUG
25LOG_SHELL_LEVEL = logging.INFO
26LOG_UNCLEAN_EXIT_LEVEL = logging.WARNING
27
28def main():
29 """Main function."""
30
31 # prepare configuration
32 args = configure_args()
33 warnings_handler = prepare_logger()
34 logging.info("Marking messages as seen from %s of %s", args.folder, args.user)
35 psw = getpass.getpass()
36
ca18dbfe 37 # prepare simple mail iterator and iterate through mailboxes
87758662 38 session = MailIterator(args.server, args.user, psw)
9d328275 39 total_messages = 0
87758662
PD
40 for mailbox in session:
41 if args.folder != "all folders" and ("INBOX/" + args.folder) not in mailbox[2]:
42 continue
43 try:
44 mail_ids = session.fetch_messages()
45 except UserWarning as ex:
46 logging.error(ex)
47 continue
9d328275
PD
48 try:
49 if len(mail_ids) > 0:
50 mail_id_range = min(mail_ids, key=int).decode('iso-8859-1') + ':' + max(mail_ids, key=int).decode('iso-8859-1')
51 session.set_seen_messages(mail_id_range)
52 total_messages += len(mail_ids)
53 except UserWarning as ex:
54 logging.error(ex)
55
56 logging.info("Finished marking %s messages as seen", total_messages)
57 logging.info("Exiting with code %s", warnings_handler.detected_problems)
87758662
PD
58 return int(warnings_handler.detected_problems > 0)
59
60def configure_args():
61 """Configure arguments and return them."""
62
63 # parse arguments
64 parser = argparse.ArgumentParser(description="Tool to mark messages as seen.")
65 parser.add_argument('-u', '--user', dest='user', action='store',
66 required=True, help='mark all messages as seen for a single user')
67 parser.add_argument('-f', '--folder', dest='folder', action='store',
68 default="all folders", help='only mark given folder as seen')
69 parser.add_argument('-s', '--server', dest='server', action='store',
70 default="localhost", help='imap server name with default localhost')
71 args = parser.parse_args()
72
73 return args
74
75def prepare_logger():
76 """Sets up the logging functionality"""
77
78 # reset the log
79 with open(LOG_FILENAME, 'w'):
80 pass
81
82 # add basic configuration
83 logging.basicConfig(filename=LOG_FILENAME,
84 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
85 level=LOG_FILE_LEVEL)
86
87 # add a handler for a console output
88 default_logger = logging.getLogger('')
89 console = logging.StreamHandler()
90 console.setLevel(LOG_SHELL_LEVEL)
91 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
92 console.setFormatter(formatter)
93 default_logger.addHandler(console)
94
95 # add a handler for warnings counting
96 warnings_handler = WarningsHandler()
97 warnings_handler.setLevel(LOG_UNCLEAN_EXIT_LEVEL)
98 default_logger.addHandler(warnings_handler)
99
100 return warnings_handler
101
102if __name__ == "__main__":
103 main()