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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
|
#!/usr/bin/env python3
# note http://docs.python.org/lib/module-doctest.html
# resp. file:///usr/share/doc/python-docs-*/html/lib/module-doctest.html
import argparse
import collections
import configparser
import email
import email.header
import email.utils
import locale
import logging
import imaplib
import os
import re
import sys
from datetime import date, timedelta
logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s',
stream=sys.stdout, level=logging.INFO)
log = logging.getLogger('imapArch')
Capas = collections.namedtuple('Capas', ['MOVE', 'UIDPLUS'])
SEP_RE = re.compile(r'\s+"([/.])"\s+')
FOLDER_RE = re.compile(r'\s+"[/.]"\s+')
class Message(object):
"""Abstraction over one email message."""
def __init__(self, folder, uid):
self.folder = folder
self.box = self.folder.box
self.uid = uid
self.msg = self.__get_body()
date_header = self.msg['Date']
try:
self.date = email.utils.parsedate_to_datetime(date_header)
except (TypeError, ValueError):
log.warning('Cannot parse date string %s', date_header)
self.date = None
self.subject = self.__get_subject()
def __get_body(self):
typ, data = self.box.uid('FETCH', '%s (RFC822)' % self.uid)
if typ == 'OK':
return email.message_from_bytes(data[0][1])
else:
raise IOError('Cannot parse message %s:\n%s!' %
(self.uid, data[0][1]))
def __get_subject(self):
out_str = ''
subj_str = self.msg['Subject']
if subj_str is not None:
for raw_str, enc in email.header.decode_header(subj_str):
if enc == 'windows-874':
enc = 'iso8859_11'
elif enc is None or ('unknown' in enc):
enc = None
if isinstance(raw_str, bytes):
try:
out_str += raw_str.decode(enc or 'utf8', 'replace')
except LookupError:
log.error('Cannot find encoding %s', enc)
raise
else:
out_str += raw_str
return out_str
def __str__(self):
return "%s in %s: %s (%s)" % (self.uid, self.folder.fld_name,
self.subject, self.date)
class Folder(object):
def __init__(self, server, fld_name, create=False):
self.server = server
self.box = server.box
self.fld_name = fld_name
self.selected = False
self.__create_missing = create
self.folder_sep = self.__get_separator()
log.debug('self.__create_missing = %s, fld_name = %s, exists %s',
self.__create_missing, fld_name,
fld_name not in self.server.all_folders)
if self.__create_missing and (fld_name not in self.server.all_folders):
self.__create_folder()
def select(self):
ok, _ = self.box.select(mailbox=self.fld_name)
if ok != 'OK':
raise IOError('Cannot select folder %s' % self.fld_name)
self.selected = True
return self
def __create_folder(self):
sep = self.folder_sep
split_name = self.fld_name.split(sep)
log.debug('split_name = %s', split_name)
target = ''
for part in split_name:
log.debug('part = %s', part)
target += '{}{}'.format(part, self.folder_sep)
fld = target.strip(self.folder_sep)
log.debug('fld = %s', fld)
if fld not in self.server.all_folders:
log.debug('Creating folder %s', fld)
self.box.create(fld)
self.server.all_folders.append(fld)
self.box.subscribe(fld)
def __list_folder(self, name=None, wildcards='*'):
if name is None:
name = '{}/'.format(self.fld_name)
ok, data = self.box.list(name, wildcards)
if ok != 'OK':
raise IOError('Cannot list folder %s' % self.fld_name)
log.debug('data = %s', data)
return data[0]
def __get_separator(self):
# type: () -> None
"""
Find current folder hierarchy separator, either from the current
folder, or if it doesn't exist from INBOX.
"""
data = self.__list_folder()
if data is None:
data = self.__list_folder('""', '""')
parse_data = SEP_RE.search(data.decode())
if parse_data is not None:
return parse_data.group(1)
else:
raise IOError('Cannot find folder separator from %s' % data)
def __emails_search(self, search_type, date_str):
ok, res = self.box.uid('SEARCH',
'%s %s' % (search_type.upper(), date_str))
if ok != 'OK':
raise IOError('SEARCH %s %s failed!' %
(search_type.lower(), date_str))
msgs = []
uids = res[0].decode().split()
for uid in uids:
msgs.append(Message(self, uid))
return msgs
def emails_before(self, before_str):
return self.__emails_search('BEFORE', before_str)
def get_archive_folder(self, msg, aroot):
raw_name = self.folder_sep.join((aroot, msg.date.strftime("%Y"),
self.fld_name))
return raw_name.strip('/')
def move_messages(self, messages):
assert self.selected is False, 'Target folder should not be selected.'
if self.box.features_present.MOVE:
# We cannot move self.box.uid('MOVE', messages, self.fld_name)
# because IMAP4_SSL.uid has a protection against unknown
# commands. https://bugs.python.org/issue33336
typ, dat = self.box._simple_command('UID', 'MOVE',
messages, self.fld_name)
ok, data = self.box._untagged_response(typ, dat, 'MOVE')
log.debug('MOVE ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot move messages to folder %s' %
self.fld_name)
elif self.box.features_present.UIDPLUS:
ok, data = self.box.uid('COPY', messages, self.fld_name)
log.debug('COPY ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot copy messages to folder %s' %
self.fld_name)
ok, data = self.box.uid('STORE',
r'+FLAGS.SILENT (\DELETED)', messages)
log.debug('STORE ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot delete messages-')
ok, data = self.box.uid('EXPUNGE', messages)
log.debug('EXPUNGE ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot expunge messages.')
else:
ok, data = self.box.uid('COPY', messages, self.fld_name)
log.debug('COPY ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot copy messages to folder %s' %
self.fld_name)
ok, data = self.box.uid('STORE',
r'+FLAGS.SILENT (\DELETED)', messages)
log.debug('STORE ok = %s, data = %s', ok, data)
if ok != 'OK':
raise IOError('Cannot delete messages-')
class EmailServer(object):
def __init__(self, serverKey=None, archive_root=None, verbosity=0):
config = self.get_config()
acc_name = serverKey if serverKey is not None \
else config['general']['account']
self.cfg = dict(config.items(acc_name))
self.archive_root = archive_root
self.box, self.all_folders = self.__login(**self.cfg)
if verbosity > 1:
self.box.debug = 4
def __login(self, host='localhost', username=None, password=None,
ssl=None):
box = imaplib.IMAP4_SSL(host=host)
ok, data = box.login(username, password)
if ok != 'OK':
raise IOError('Cannot login with credentials %s' %
str((host, username, password,)))
ok, data = box.capability()
capas = data[0].decode()
log.debug('capas = %s', capas)
box.features_present = Capas._make(
['MOVE' in capas, 'UIDPLUS' in capas])
ok, data = box.list()
if ok != 'OK':
raise IOError('Cannot list folders!')
folders = [FOLDER_RE.split(x.decode())[1] for x in data]
return box, folders
@staticmethod
def get_config():
# In case the configuration file is missing, only empty list will be
# returned
config = configparser.ConfigParser()
config.read(os.path.expanduser('~/.config/imap_archiver.cfg'))
return config
def archive_folder(self, folder_name, before_date):
# type: (str, date) -> None
"""
Archive one folder to the proper archiving positioins.
:param: folder_name
:param: before_date
"""
print('Archiving {}'.format(folder_name))
copy_cache = {}
fld = Folder(self, folder_name).select()
before_str = before_date.strftime('%d-%b-%Y')
for msg in fld.emails_before(before_str):
sys.stdout.write('.')
if msg.date is not None:
arch_folder = fld.get_archive_folder(msg, self.archive_root)
if arch_folder in copy_cache:
copy_cache[arch_folder].append(msg)
else:
copy_cache[arch_folder] = [msg]
sys.stdout.write('\n')
for key in copy_cache:
log.debug('***** %s:', key)
for msg in copy_cache[key]:
log.debug('\tmsg: %s', str(msg))
# Go through the cache and make moves.
for arch_dir in copy_cache:
msg_ids = ','.join([x.uid for x in copy_cache[arch_dir]])
log.debug('arch_dir = %s, msgs = %s', arch_dir,
msg_ids)
dir = Folder(self, arch_dir, create=True)
dir.move_messages(msg_ids)
def list_folders(self):
return sorted(self.all_folders, key=str.lower)
def __enter__(self):
return self
def __exit__(self, *args):
if args != (None, None, None):
log.warning('args = %s', args)
self.box.close()
if __name__ == '__main__':
locale.setlocale(locale.LC_ALL, 'en_US')
argp = argparse.ArgumentParser()
subps = argp.add_subparsers(dest='cmd')
subp_servers = subps.add_parser('servers',
help='List available servers (by keywords)')
subp_list = subps.add_parser('list', help='List all folders')
subp_arc = subps.add_parser('archive', help='Archive folder[s]')
subp_arc.add_argument('-d', type=int, default=14, dest='days',
help='How old messages we should keep')
subp_arc.add_argument('-s', '--server',
help='Symbolic name of the server to be used')
subp_arc.add_argument('folder', help='Folder which should be archived')
subp_arc.add_argument('archive',
help='Root folder to store annual archives to')
argp.add_argument('-v', action='count', dest='verbosity', default=0,
help='Verbosity of the operation (-vv shows IMAP chatter)')
args = argp.parse_args()
log.debug('args = %s', args)
if args.verbosity > 0:
log.setLevel(logging.DEBUG)
if args.cmd == 'servers':
config = EmailServer.get_config()
sects = set(config.keys()) - {'DEFAULT', 'general'}
print('Available servers:\n%s' % tuple(sects))
elif args.cmd == 'list':
myStore = EmailServer(verbosity=args.verbosity)
folders = myStore.list_folders()
print('\n'.join(folders))
else:
before = date.today() - timedelta(days=args.days)
with EmailServer(args.server, args.archive, verbosity=args.verbosity) as myStore:
myStore.archive_folder(args.folder, before)
|