forked from davisdude/mbox2html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mbox2html.py
501 lines (443 loc) · 14.9 KB
/
mbox2html.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import mailbox
import email
import email.policy
import email.utils
import html
import urllib.parse
import chardet
import base64
import struct
import copy
import re
import os
import shutil
import math
import argparse
import uuid
def flatten(l):
for i in l:
if isinstance(i, list):
yield from flatten(i)
else:
yield i
# Puts date into consistent format
def format_date(msg, listing=False):
msg_date = msg.get("date")
try:
date = email.utils.parsedate_to_datetime(msg_date)
if listing:
return date.isoformat()
else:
return email.utils.format_datetime(date)
except ValueError:
return msg_date
# Helps extracting tricky header info (at times needed for Subject and From)
def get_header_text(msg, item, default="utf-8"):
header_text = msg.get(item)
try:
headers = email.header.decode_header(header_text)
except Exception:
return
header_sections = []
for text, charset in headers:
if charset is None:
try:
encoding = chardet.detect(text)["encoding"]
header_section = text.decode(encoding)
except Exception:
header_section = text
else:
try:
header_section = text.decode(charset)
except Exception:
header_section = text.decode(
default,
errors="backslashreplace"
)
if header_section:
header_sections.append(header_section)
return " ".join(header_sections)
def get_payload_text(msg):
subtype = msg.get_content_subtype()
payload = msg.get_payload(decode=True)
if payload is None:
return ""
charset = msg.get_charset() or chardet.detect(payload)["encoding"]
content = payload.decode(charset or "utf-8", errors="backslashreplace")
if subtype == "plain":
return html.escape(content).replace("\n", "<br>")
else:
return content
def payload_get_type(payload, types, type_list):
for t in type_list:
if t in types:
return get_payload_text(payload[types.index(t)])
# TODO: Is this possible? Testing indicates no
def parse_email(msg):
try:
content_type = msg.get_content_type()
except Exception:
content_type = "text/plain"
try:
maintype = msg.get_content_maintype()
except Exception:
maintype = "text"
try:
subtype = msg.get_content_subtype()
except Exception:
subtype = None
pass
try:
payload = msg.get_payload()
except Exception:
return
if maintype == "text":
return [
{
"name": msg.get_filename(),
"content": get_payload_text(msg),
"type": "text",
}
]
elif maintype == "multipart":
if subtype == "alternative":
# TODO: Can this contain non-text?
try:
types = [m.get_content_type() for m in payload]
if args.mode == "plain":
type_list = ["text/plain"]
else:
type_list = ["text/html", "text/plain"]
return [
{
"name": msg.get_filename(),
"content": payload_get_type(payload, types, type_list),
"type": "text",
}
]
except:
pass
else:
return list(flatten([parse_email(p) for p in payload]))
elif content_type == "message/rfc822":
return list(flatten([parse_email(p) for p in payload]))
elif content_type == "application/pgp-signature":
return [
{
"name": None, # Include in body
"content": msg.get_payload().replace("\n", "<br>"),
"type": "text",
}
]
elif content_type != "message/delivery-status":
return [
{
"name": msg.get_filename(),
"content": msg.get_payload(decode=True),
"type": content_type,
}
]
def filler_message(mid):
m = mailbox.Message()
m["message-id"] = mid
m["subject"] = "[Not in archive]"
m["date"] = "[Not in archive]"
m["from"] = ""
return m
def safely_append_thread(mid, par, threads, messages):
if par is None:
return
if mid not in threads:
threads[mid] = []
if par not in threads:
threads[par] = []
if mid not in threads[par]:
threads[par].append(mid)
# Creates filler if missing
if par not in messages:
messages[par] = filler_message(par)
if mid not in messages:
messages[mid] = filler_message(mid)
if messages[mid].get("in-reply-to") is None:
messages[mid]["in-reply-to"] = par
def get_parent_id(msg):
irt = msg.get("in-reply-to")
if irt is not None:
return irt
refs = msg.get("references")
if refs is not None:
return refs[-1]
return None
# Establishes hierarchical thread relations
# (Also modifies in in-reply-to field if needed for later use)
# TODO: Implement https://www.jwz.org/doc/threading.html
# Current implementation assumes Message-IDs are consistent between parent and
# child (which is not always the case), and requires manual intervention in
# this case, and in the case where fields aren't filled out consistently
def get_threads(messages):
threads = {} # Contains direct children
for mid, msg in messages.copy().items():
if mid not in threads:
threads[mid] = []
# Adds IRT content (if available)
irt = msg.get("in-reply-to")
safely_append_thread(mid, irt, threads, messages)
# Adds references content (if available)
# References are (typically) hierarchical: 1st is parent of 2nd, 2nd of 3rd, etc.
# TODO: Not guaranteed to be separated by spaces
refs = re.findall(r"\S+", msg.get("references") or "")
if (irt is not None) and (irt not in refs):
refs.append(irt)
for parent, child in zip(refs, refs[1:]):
safely_append_thread(child, parent, threads, messages)
# Pruning pass - ensure each thread only has 1 parent
for mid, children in threads.items():
for c in children.copy():
if get_parent_id(messages[c]) != mid:
children.remove(c)
# TODO: Find dead roots; attempt to connect to other threads
return threads
def content_to_html(msg, content, threads, messages, outdir, body_path):
if content is None:
return
# Writes body of html/header info
with open(body_path, "w") as file:
file.write(
"""
<html>
<head>
<title>%s</title>
</head>
<body>
<p><a href="index.html">Index</a></p>
<p><strong>Subject</strong>: %s</p>
<p><strong>From</strong>: %s</p>
<p><strong>Date</strong>: %s</p>
"""
% (
"%s - %s - %s"
% (
html.escape(get_header_text(msg, "subject")),
html.escape(format_date(msg)),
"Email Archive",
),
html.escape(get_header_text(msg, "subject")),
html.escape(get_header_text(msg, "from")),
html.escape(format_date(msg)),
)
)
# Parent info
parent = get_parent_id(msg)
if parent is not None:
if parent in messages:
file.write(
"""
<p><a href="%s">Parent</a></p>
"""
% (urllib.parse.quote(parent) + ".html")
)
else:
file.write(
"""
<p><em>Parent not archived</em></p>
"""
)
# Writes message content
attachments = []
for part in content:
if part is None:
continue
name = part["name"]
# Append for multi-part messages/body
if name is None:
name = msg_id + ".html"
filepath = body_path
# hr to distinguish content
if part["content"]:
try:
part["content"] = "<hr>" + part["content"]
except Exception:
pass
# For attachments, just create the director if needed
else:
os.makedirs(attachment_path, exist_ok=True)
filepath = os.path.join(attachment_path, name)
attachments.append({"name": name, "path": filepath})
if part["content"]:
if part["type"] == "text":
# TODO: Attempt to detect encoding?
try:
open(filepath, "a").write(part["content"])
except UnicodeEncodeError:
open(filepath, "a", encoding="utf8").write(part["content"])
else:
open(filepath, "ab").write(part["content"])
# Finishes body/writes footer info
with open(body_path, "a") as file:
if len(attachments) > 0:
# Attachments portion of footer
file.write(
"""
<hr>
<p><strong>Attachments</strong>:</p>
<p><em>(Please be wary of attachments - they have not been scanned for viruses)</em></p>
<ul>
%s
</ul>
"""
% (
"\n".join(
[
'<li><a href="../%s">%s</a>'
% (urllib.parse.quote(a["path"]), a["name"])
for a in attachments
]
)
)
)
# Replies
if len(threads[msg_id]) > 0:
file.write(
"""
<hr>
<p><strong>Replies</strong>:</p>
<ul>
%s
</ul>
"""
% (
"\n".join(
[
'<li><a href="%s">%s</a>'
% (
urllib.parse.quote(child + ".html"),
html.escape(
get_header_text(messages[child], "subject")
),
)
for child in threads[msg_id]
]
)
)
)
# Finishes body
file.write(
"""
</body>
</html>
"""
)
def write_message_tree(file, msg_ids, threads, messages):
for mid in msg_ids:
msg = messages[mid]
file.write(
"<li>%s: %s</li>"
% (
html.escape(format_date(msg, listing=True)),
'<a href="%s">%s</a>'
% (
urllib.parse.quote(mid.replace("/", "-") + ".html"),
get_header_text(msg, "subject"),
),
)
)
if len(threads[mid]) > 0:
file.write("<ul>")
write_message_tree(file, threads[mid], threads, messages)
file.write("</ul>")
def sort_helper(msg, messages):
if isinstance(msg, str):
return sort_helper(messages[msg], messages)
# 10 = number of elements in date tuple
# TODO: Potentially infer time?
return email.utils.parsedate_tz(msg.get("date")) or 10 * (math.inf,)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("mboxfile", default="export.mbox", help="path to mbox file")
parser.add_argument("outdir", default="email-archive", help="output directory")
parser.add_argument(
"-f",
"--recipient-filter",
help="filter by to/cc:/rto: recipient (e.g. by mailinglist)",
)
parser.add_argument(
"-m",
"--mode",
choices=["plain", "html"],
default="html",
help="multipart mime-type to extract, default: text/html",
)
args = parser.parse_args()
filename = args.mboxfile
outdir = args.outdir
recipient_filter = args.recipient_filter
mode = args.mode
if not os.path.isfile(filename):
print(f'path "{filename}" is not a file')
exit(1)
if not os.path.exists(outdir):
os.makedirs(outdir)
mbox = mailbox.mbox(filename)
messages = {}
print(f"Processing {filename}")
for key, msg in mbox.items():
print(msg.get("message-id"))
to = msg.get("to") or msg.get("delivered-to") or ""
cc = msg.get("cc") or ""
rto = msg.get("reply-to") or ""
if recipient_filter:
if (
(to.find(recipient_filter) >= 0)
or (cc.find(recipient_filter) >= 0)
or (rto.find(recipient_filter) >= 0)
):
messages[msg.get("message-id")] = msg
elif msg.get("message-id"):
messages[msg.get("message-id")] = msg
else:
print(f'"{key}" has no message-id')
continue
# Gets parental info
threads = get_threads(messages)
# Sorts replies to be in order
for mid, msgs in threads.copy().items():
threads[mid].sort(key=lambda x: sort_helper(x, messages))
# Writes email html files
for key, msg in messages.items():
if msg.get("message-id"):
msg_id = msg.get("message-id")
else:
msg_id = str(uuid.uuid4())
body_path = os.path.join(outdir, msg_id.replace("/", "-") + ".html")
attachment_path = os.path.join(outdir, msg_id.replace("/", "-"))
# Deletes all previous files (if they exist) for easier append-age later
try:
os.remove(body_path)
except OSError:
pass
shutil.rmtree(attachment_path, ignore_errors=True)
content = parse_email(msg)
content_to_html(msg, content, threads, messages, outdir, body_path)
# Writes index.html
# Sorts files based on timestamp; makes things easier
sorted_messages = [x for x in messages.values()]
sorted_messages.sort(key=lambda x: sort_helper(x, messages))
roots = [f.get("message-id") for f in sorted_messages if get_parent_id(f) is None]
with open(os.path.join(outdir, "index.html"), "w") as file:
file.write(
"""
<html>
<head>
<title>Email Archive</title>
</head>
<body>
<ul>"""
)
write_message_tree(file, roots, threads, messages)
file.write(
"""
</ul>
</body>
</html>
"""
)