forked from polo2ro/imapbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimapbox.py
152 lines (120 loc) · 6.23 KB
/
imapbox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from mailboxresource import save_emails, get_folder_fist
import argparse
from six.moves import configparser
import os
import getpass
import logging
# choose between DEBUG (log every information) or warning (change of state) or CRITICAL (only error)
#logLevel=logging.CRITICAL # CRITICAL ONLY
#logLevel=logging.ERROR # CRITICAL ERROR ONLY
logLevel=logging.WARNING # CRITICAL ERROR WARNING ONLY
#logLevel=logging.INFO # CRITICAL ERROR WARNING INFO ONLY
#logLevel=logging.DEBUG # CRITICAL ERROR WARNING INFO DEBUG ONLY
logOutFilename = '/tmp/imapbox.log'
if 'logOutFilename' in globals() :
#logging.basicConfig(filename=logOutFilename,level=logLevel, format='%(asctime)s -- %(name)s ; %(levelname)s ; %(message)s')
logging.basicConfig(filename=logOutFilename,level=logLevel, format='%(asctime)s ; %(levelname)s ; %(message)s')
else:
#logging.basicConfig(level=logLevel, format='%(asctime)s -- %(name)s ; %(levelname)s ; %(message)s')
logging.basicConfig(level=logLevel, format='%(asctime)s ; %(levelname)s ; %(message)s')
alert_mail = '.'
error_alert_mail = 0
def load_configuration(args):
global alert_mail
config = configparser.ConfigParser(allow_no_value=True)
config.read(['config.cfg', '/etc/imapbox/config.cfg', os.path.expanduser('~/.config/imapbox/config.cfg')])
options = {
'days': None,
#'local_folder': '.',
'wkhtmltopdf': None,
'exclude': [],
'alert_mail': '.',
'accounts': []
}
if (config.has_section('imapbox')):
if config.has_option('imapbox', 'days'):
options['days'] = config.getint('imapbox', 'days')
if config.has_option('imapbox', 'local_folder'):
options['local_folder'] = os.path.expanduser(config.get('imapbox', 'local_folder'))
if config.has_option('imapbox', 'alert_mail'):
#options['alert_mail'] = os.path.expanduser(config.get('imapbox', 'alert_mail'))
alert_mail = os.path.expanduser(config.get('imapbox', 'alert_mail'))
if config.has_option('imapbox', 'wkhtmltopdf'):
options['wkhtmltopdf'] = os.path.expanduser(config.get('imapbox', 'wkhtmltopdf'))
if config.has_option('imapbox', 'exclude'):
options['exclude'] = os.path.expanduser(config.get('imapbox', 'exclude'))
for section in config.sections():
if ('imapbox' == section):
continue
if (args.specific_account and (args.specific_account != section)):
continue
account = {
'name': section,
'local_folder': '.',
'remote_folder': 'INBOX',
'port': 993,
'ssl': False,
}
account['host'] = config.get(section, 'host')
if config.has_option(section, 'port'):
account['port'] = config.get(section, 'port')
account['username'] = config.get(section, 'username')
if config.has_option(section, 'password'):
account['password'] = config.get(section, 'password')
else:
prompt=('Password for ' + account['username'] + ':' + account['host'] + ': ')
account['password'] = getpass.getpass(prompt=prompt)
if config.has_option(section, 'ssl'):
if config.get(section, 'ssl').lower() == "true":
account['ssl'] = True
if config.has_option(section, 'remote_folder'):
account['remote_folder'] = config.get(section, 'remote_folder')
if config.has_option(section, 'local_folder'):
account['local_folder'] = config.get(section, 'local_folder')
if (None == account['host'] or None == account['username'] or None == account['password']):
continue
options['accounts'].append(account)
if (args.local_folder):
options['local_folder'] = args.local_folder
if (args.days):
options['days'] = args.days
if (args.wkhtmltopdf):
options['wkhtmltopdf'] = args.wkhtmltopdf
return options
def main():
global alert_mail
global error_alert_mail
try:
argparser = argparse.ArgumentParser(description="Dump a IMAP folder into .eml files")
argparser.add_argument('-l', dest='local_folder', help="Local folder where to create the email folders")
argparser.add_argument('-d', dest='days', help="Number of days back to get in the IMAP account", type=int)
argparser.add_argument('-w', dest='wkhtmltopdf', help="The location of the wkhtmltopdf binary")
argparser.add_argument('-a', dest='specific_account', help="Select a specific account to backup")
args = argparser.parse_args()
options = load_configuration(args)
for account in options['accounts']:
logging.warning('{}/{} (on {})'.format(account['name'], account['remote_folder'], account['host']))
if account['remote_folder'] == "__ALL__":
#basedir = options['local_folder']
basedir = account['local_folder']
for folder_entry in get_folder_fist(account):
folder_name = folder_entry.decode().replace("/",".").split(' "." ')
account['remote_folder'] = folder_name[1]
account['local_folder'] = os.path.join(basedir, account['remote_folder'])
logging.warning("Saving folder: %s to %s", folder_name[1], basedir)
if account['remote_folder'] != '"[Gmail]"' and not 'Spam' in account['remote_folder'] and not 'Junk' in account['remote_folder']:
error_alert_mail = save_emails(account, options)
else:
logging.warning('Saving folder: %s to %s',account['remote_folder'], account['local_folder'])
error_alert_mail = save_emails(account, options)
except Exception as e:
error_alert_mail += 1
logging.exception("main crashed. Error: %s, %s erreurs de sauvegarde", e, error_alert_mail)
print(e)
logging.critical("%s erreurs de sauvegarde", error_alert_mail)
if error_alert_mail >= 1 and alert_mail != '.':
os.system('echo \'Erreur sauvegarde mail IMAPBOX '+ str(error_alert_mail) +' erreurs\' | mail -s \'Erreur sauvegarde mail\' '+alert_mail)
if __name__ == '__main__':
main()