mailbox-backup 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
import argparse
|
|
3
|
+
import base64
|
|
4
|
+
import email
|
|
5
|
+
import fnmatch
|
|
6
|
+
import getpass
|
|
7
|
+
import imaplib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
from email.header import decode_header
|
|
14
|
+
from email.message import Message
|
|
15
|
+
from email.parser import BytesHeaderParser
|
|
16
|
+
from email.utils import parseaddr, parsedate_to_datetime
|
|
17
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from tqdm import tqdm
|
|
21
|
+
from tqdm.contrib.logging import logging_redirect_tqdm
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
__version__ = version("mailbox-backup")
|
|
27
|
+
except PackageNotFoundError:
|
|
28
|
+
__version__ = "unknown"
|
|
29
|
+
|
|
30
|
+
DEFAULT_FILENAME_TEMPLATE = "{date}-{time}_{subject:.80} ({sender})"
|
|
31
|
+
DEFAULT_DATE_FORMAT = "%Y%m%d"
|
|
32
|
+
DEFAULT_TIME_FORMAT = "%H%M%S"
|
|
33
|
+
|
|
34
|
+
INDEX_FILENAME = ".imap_index.json"
|
|
35
|
+
MAX_FILENAME_BYTES = 255
|
|
36
|
+
WINDOWS_MAX_PATH = 255
|
|
37
|
+
WINDOWS_RESERVED_NAMES = {
|
|
38
|
+
"CON",
|
|
39
|
+
"PRN",
|
|
40
|
+
"AUX",
|
|
41
|
+
"NUL",
|
|
42
|
+
*(f"COM{i}" for i in range(1, 10)),
|
|
43
|
+
*(f"LPT{i}" for i in range(1, 10)),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def decode_mutf7(text: str) -> str:
|
|
48
|
+
"""Decode IMAP modified UTF-7 folder names into standard Unicode strings."""
|
|
49
|
+
result = []
|
|
50
|
+
i = 0
|
|
51
|
+
length = len(text)
|
|
52
|
+
while i < length:
|
|
53
|
+
if text[i] == "&":
|
|
54
|
+
end = text.find("-", i)
|
|
55
|
+
if end == -1:
|
|
56
|
+
result.append(text[i:])
|
|
57
|
+
break
|
|
58
|
+
if end == i + 1:
|
|
59
|
+
result.append("&")
|
|
60
|
+
else:
|
|
61
|
+
b64_part = text[i + 1 : end].replace(",", "/")
|
|
62
|
+
b64_part += "=" * ((4 - len(b64_part) % 4) % 4)
|
|
63
|
+
try:
|
|
64
|
+
decoded = base64.b64decode(b64_part).decode("utf-16-be")
|
|
65
|
+
result.append(decoded)
|
|
66
|
+
except Exception:
|
|
67
|
+
result.append(text[i : end + 1])
|
|
68
|
+
i = end + 1
|
|
69
|
+
else:
|
|
70
|
+
result.append(text[i])
|
|
71
|
+
i += 1
|
|
72
|
+
return "".join(result)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def decode_mime_words(value: str | None, fallback: str = "unknown") -> str:
|
|
76
|
+
"""Decode MIME encoded-word headers (e.g. =?UTF-8?Q?...?=)."""
|
|
77
|
+
if not value:
|
|
78
|
+
return fallback
|
|
79
|
+
fragments = decode_header(value)
|
|
80
|
+
decoded_parts = []
|
|
81
|
+
for fragment, encoding in fragments:
|
|
82
|
+
if isinstance(fragment, bytes):
|
|
83
|
+
decoded_parts.append(fragment.decode(encoding or "utf-8", errors="replace"))
|
|
84
|
+
else:
|
|
85
|
+
decoded_parts.append(fragment)
|
|
86
|
+
text = "".join(decoded_parts).strip()
|
|
87
|
+
return text if text else fallback
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def extract_address(header_value: str | None) -> str:
|
|
91
|
+
"""Extract a clean email address or display name from From/To headers."""
|
|
92
|
+
if not header_value:
|
|
93
|
+
return "unknown"
|
|
94
|
+
decoded = decode_mime_words(header_value, fallback="unknown")
|
|
95
|
+
name, addr = parseaddr(decoded)
|
|
96
|
+
return addr if addr else (name or "unknown")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def sanitize_component(name: str, max_len: int | None = None) -> str:
|
|
100
|
+
"""Sanitize a string so it is safe as a filename or directory name on Windows/Linux/macOS."""
|
|
101
|
+
cleaned = re.sub(r'[\\/*?:"<>|\x00-\x1f]+', "_", name)
|
|
102
|
+
cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
|
|
103
|
+
if max_len is not None and len(cleaned) > max_len:
|
|
104
|
+
cleaned = cleaned[:max_len].strip(" .")
|
|
105
|
+
if not cleaned:
|
|
106
|
+
return "unnamed"
|
|
107
|
+
if cleaned.upper() in WINDOWS_RESERVED_NAMES:
|
|
108
|
+
cleaned = f"_{cleaned}"
|
|
109
|
+
return cleaned
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def truncate_utf8_bytes(text: str, max_bytes: int) -> str:
|
|
113
|
+
"""Truncate a string so its UTF-8 encoding does not exceed max_bytes."""
|
|
114
|
+
encoded = text.encode("utf-8")
|
|
115
|
+
if len(encoded) <= max_bytes:
|
|
116
|
+
return text
|
|
117
|
+
return encoded[:max_bytes].decode("utf-8", errors="ignore").strip(" .")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def resolve_unique_path(
|
|
121
|
+
folder_path: Path,
|
|
122
|
+
base_name: str,
|
|
123
|
+
ext: str = ".eml",
|
|
124
|
+
current_path: Path | None = None,
|
|
125
|
+
) -> Path:
|
|
126
|
+
"""Return a non-colliding Path respecting OS filename byte limits and Windows MAX_PATH."""
|
|
127
|
+
reserve_suffix = len(ext.encode("utf-8")) + 6
|
|
128
|
+
max_bytes = MAX_FILENAME_BYTES - reserve_suffix
|
|
129
|
+
|
|
130
|
+
if os.name == "nt":
|
|
131
|
+
abs_dir_len = len(str(folder_path.resolve())) + 1
|
|
132
|
+
max_chars = WINDOWS_MAX_PATH - abs_dir_len - len(ext) - 6
|
|
133
|
+
if max_chars < 10:
|
|
134
|
+
raise OSError(f"Directory path too deep for Windows MAX_PATH: {folder_path.resolve()}")
|
|
135
|
+
base_name = base_name[:max_chars].strip(" .")
|
|
136
|
+
|
|
137
|
+
safe_base = truncate_utf8_bytes(base_name, max_bytes) or "unnamed"
|
|
138
|
+
|
|
139
|
+
candidate = folder_path / f"{safe_base}{ext}"
|
|
140
|
+
counter = 2
|
|
141
|
+
while candidate.exists() and candidate != current_path:
|
|
142
|
+
candidate = folder_path / f"{safe_base}-{counter}{ext}"
|
|
143
|
+
counter += 1
|
|
144
|
+
return candidate
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def build_base_filename(msg: Message, uid: str, args: argparse.Namespace) -> str:
|
|
148
|
+
"""Build sanitized base filename from email headers using CLI format options."""
|
|
149
|
+
date_str = "0000-00-00"
|
|
150
|
+
time_str = "0000"
|
|
151
|
+
if msg["Date"]:
|
|
152
|
+
try:
|
|
153
|
+
dt = parsedate_to_datetime(msg["Date"])
|
|
154
|
+
date_str = dt.strftime(args.date_format)
|
|
155
|
+
time_str = dt.strftime(args.time_format)
|
|
156
|
+
except Exception:
|
|
157
|
+
logger.debug("Could not parse Date header for UID %s: %s", uid, msg["Date"])
|
|
158
|
+
|
|
159
|
+
fields = {
|
|
160
|
+
"date": sanitize_component(date_str),
|
|
161
|
+
"time": sanitize_component(time_str),
|
|
162
|
+
"sender": sanitize_component(extract_address(msg["From"])),
|
|
163
|
+
"recipient": sanitize_component(extract_address(msg["To"])),
|
|
164
|
+
"subject": sanitize_component(decode_mime_words(msg["Subject"], "no_subject")),
|
|
165
|
+
"uid": uid,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
return sanitize_component(args.format.format(**fields))
|
|
170
|
+
except KeyError as exc:
|
|
171
|
+
logger.error("Invalid placeholder in --format: %s", exc)
|
|
172
|
+
sys.exit(1)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def parse_folder_list(raw_folders: list[bytes]) -> list[tuple[str, str]]:
|
|
176
|
+
"""Parse IMAP LIST output into a list of (delimiter, raw_folder_name) tuples."""
|
|
177
|
+
folders: list[tuple[str, str]] = []
|
|
178
|
+
pattern = re.compile(r'^\([^)]*\)\s+(?:"([^"]+)"|NIL)\s+(?:"(.*)"|(.*))$')
|
|
179
|
+
for item in raw_folders:
|
|
180
|
+
decoded = item.decode("ascii", errors="replace").strip()
|
|
181
|
+
match = pattern.match(decoded)
|
|
182
|
+
if not match:
|
|
183
|
+
logger.debug("Could not parse folder line: %s", decoded)
|
|
184
|
+
continue
|
|
185
|
+
delimiter = match.group(1) or "/"
|
|
186
|
+
folder_name = match.group(2) if match.group(2) is not None else match.group(3)
|
|
187
|
+
if folder_name:
|
|
188
|
+
folders.append((delimiter, folder_name))
|
|
189
|
+
return folders
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def is_excluded(
|
|
193
|
+
folder_display_name: str,
|
|
194
|
+
delimiter: str,
|
|
195
|
+
patterns: list[str],
|
|
196
|
+
) -> bool:
|
|
197
|
+
"""Check if a folder or any of its parent folders matches an exclusion glob pattern."""
|
|
198
|
+
if not patterns:
|
|
199
|
+
return False
|
|
200
|
+
|
|
201
|
+
parts = folder_display_name.split(delimiter)
|
|
202
|
+
slash_prefixes = ["/".join(parts[:i]) for i in range(1, len(parts) + 1)]
|
|
203
|
+
raw_prefixes = [delimiter.join(parts[:i]) for i in range(1, len(parts) + 1)] if delimiter != "/" else []
|
|
204
|
+
|
|
205
|
+
for pat in patterns:
|
|
206
|
+
clean_slash_pat = pat.rstrip("/")
|
|
207
|
+
if any(fnmatch.fnmatchcase(p, clean_slash_pat) for p in slash_prefixes):
|
|
208
|
+
return True
|
|
209
|
+
|
|
210
|
+
if raw_prefixes:
|
|
211
|
+
clean_raw_pat = pat.rstrip(delimiter)
|
|
212
|
+
if any(fnmatch.fnmatchcase(p, clean_raw_pat) for p in raw_prefixes):
|
|
213
|
+
return True
|
|
214
|
+
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def fetch_uid_sizes(imap: imaplib.IMAP4_SSL) -> dict[str, int]:
|
|
219
|
+
"""Fetch mapping of UID -> RFC822.SIZE for all messages in the currently selected folder."""
|
|
220
|
+
status, data = imap.uid("fetch", "1:*", "(UID RFC822.SIZE)")
|
|
221
|
+
if status != "OK" or not data or data == [None]:
|
|
222
|
+
return {}
|
|
223
|
+
|
|
224
|
+
uid_sizes: dict[str, int] = {}
|
|
225
|
+
uid_pattern = re.compile(rb"UID\s+(\d+)")
|
|
226
|
+
size_pattern = re.compile(rb"RFC822\.SIZE\s+(\d+)")
|
|
227
|
+
|
|
228
|
+
for item in data:
|
|
229
|
+
raw_line = item[0] if isinstance(item, tuple) else item
|
|
230
|
+
if not isinstance(raw_line, bytes):
|
|
231
|
+
continue
|
|
232
|
+
uid_match = uid_pattern.search(raw_line)
|
|
233
|
+
size_match = size_pattern.search(raw_line)
|
|
234
|
+
if uid_match and size_match:
|
|
235
|
+
uid_sizes[uid_match.group(1).decode("ascii")] = int(size_match.group(1))
|
|
236
|
+
return uid_sizes
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def load_password(args: argparse.Namespace) -> str:
|
|
240
|
+
"""Resolve IMAP password from CLI arg, file, or interactive prompt."""
|
|
241
|
+
if args.password_file:
|
|
242
|
+
pw_path: Path = args.password_file
|
|
243
|
+
if not pw_path.is_file():
|
|
244
|
+
logger.error("Password file not found: %s", pw_path)
|
|
245
|
+
sys.exit(1)
|
|
246
|
+
return pw_path.read_text(encoding="utf-8").strip()
|
|
247
|
+
if args.password:
|
|
248
|
+
return args.password
|
|
249
|
+
return getpass.getpass(f"IMAP password for {args.user}: ")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def cmd_list(imap: imaplib.IMAP4_SSL, excludes: list[str]) -> None:
|
|
253
|
+
"""List all remote folders alphabetically with their message counts."""
|
|
254
|
+
status, raw_folders = imap.list()
|
|
255
|
+
if status != "OK" or not raw_folders:
|
|
256
|
+
logger.error("Failed to retrieve folder list.")
|
|
257
|
+
return
|
|
258
|
+
|
|
259
|
+
folders = parse_folder_list(raw_folders)
|
|
260
|
+
decoded_folders = sorted(
|
|
261
|
+
((decode_mutf7(raw_name), raw_name, delimiter) for delimiter, raw_name in folders),
|
|
262
|
+
key=lambda item: item[0].casefold(),
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
logger.info("%-50s | %10s", "Remote Folder", "Messages")
|
|
266
|
+
logger.info("-" * 63)
|
|
267
|
+
|
|
268
|
+
total = 0
|
|
269
|
+
for display_name, raw_name, delimiter in decoded_folders:
|
|
270
|
+
if is_excluded(display_name, delimiter, excludes):
|
|
271
|
+
logger.debug("Excluded folder: %s", display_name)
|
|
272
|
+
continue
|
|
273
|
+
|
|
274
|
+
sel_status, count_data = imap.select(f'"{raw_name}"', readonly=True)
|
|
275
|
+
if sel_status != "OK":
|
|
276
|
+
logger.info("%-50s | %10s", display_name, "N/A")
|
|
277
|
+
continue
|
|
278
|
+
|
|
279
|
+
count = int(count_data[0])
|
|
280
|
+
total += count
|
|
281
|
+
logger.info("%-50s | %10d", display_name, count)
|
|
282
|
+
|
|
283
|
+
logger.info("-" * 63)
|
|
284
|
+
logger.info("%-50s | %10d", "TOTAL", total)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def cmd_backup(imap: imaplib.IMAP4_SSL, args: argparse.Namespace) -> None:
|
|
288
|
+
"""Download all non-excluded folders into local .eml files with size verification."""
|
|
289
|
+
status, raw_folders = imap.list()
|
|
290
|
+
if status != "OK" or not raw_folders:
|
|
291
|
+
logger.error("Failed to retrieve folder list.")
|
|
292
|
+
return
|
|
293
|
+
|
|
294
|
+
folders = parse_folder_list(raw_folders)
|
|
295
|
+
header_parser = BytesHeaderParser()
|
|
296
|
+
summary: list[tuple[str, int, int, int, int, int]] = []
|
|
297
|
+
|
|
298
|
+
# Pre-scan selectable folders to determine total remote message count
|
|
299
|
+
folder_plan: list[tuple[str, str, str, int]] = []
|
|
300
|
+
for delimiter, raw_name in folders:
|
|
301
|
+
display_name = decode_mutf7(raw_name)
|
|
302
|
+
if is_excluded(display_name, delimiter, args.exclude):
|
|
303
|
+
logger.info("Skipping excluded folder: %s", display_name)
|
|
304
|
+
continue
|
|
305
|
+
|
|
306
|
+
sel_status, count_data = imap.select(f'"{raw_name}"', readonly=True)
|
|
307
|
+
if sel_status != "OK":
|
|
308
|
+
logger.warning("Skipping unselectable folder: %s", display_name)
|
|
309
|
+
continue
|
|
310
|
+
|
|
311
|
+
folder_plan.append((delimiter, raw_name, display_name, int(count_data[0])))
|
|
312
|
+
|
|
313
|
+
total_messages = sum(count for _, _, _, count in folder_plan)
|
|
314
|
+
|
|
315
|
+
with logging_redirect_tqdm(), tqdm(total=total_messages, desc="Total", unit="mail", position=0) as total_pbar:
|
|
316
|
+
for delimiter, raw_name, display_name, server_count in folder_plan:
|
|
317
|
+
sel_status, _ = imap.select(f'"{raw_name}"', readonly=True)
|
|
318
|
+
if sel_status != "OK":
|
|
319
|
+
logger.warning("Skipping unselectable folder: %s", display_name)
|
|
320
|
+
continue
|
|
321
|
+
|
|
322
|
+
parts = [sanitize_component(p, max_len=60) for p in display_name.split(delimiter)]
|
|
323
|
+
folder_path = args.out.joinpath(*parts)
|
|
324
|
+
|
|
325
|
+
if server_count == 0:
|
|
326
|
+
local_eml_count = (
|
|
327
|
+
sum(1 for f in folder_path.iterdir() if f.is_file() and f.suffix == ".eml")
|
|
328
|
+
if folder_path.is_dir()
|
|
329
|
+
else 0
|
|
330
|
+
)
|
|
331
|
+
summary.append((display_name, 0, local_eml_count, 0, 0, 0))
|
|
332
|
+
logger.debug("Skipping empty folder: %s", display_name)
|
|
333
|
+
continue
|
|
334
|
+
|
|
335
|
+
folder_path.mkdir(parents=True, exist_ok=True)
|
|
336
|
+
|
|
337
|
+
index_path = folder_path / INDEX_FILENAME
|
|
338
|
+
uid_index: dict[str, str] = {}
|
|
339
|
+
if index_path.is_file():
|
|
340
|
+
try:
|
|
341
|
+
uid_index = json.loads(index_path.read_text(encoding="utf-8"))
|
|
342
|
+
except json.JSONDecodeError:
|
|
343
|
+
logger.warning("Corrupted index in %s, rebuilding.", folder_path)
|
|
344
|
+
|
|
345
|
+
uid_sizes = fetch_uid_sizes(imap) if server_count > 0 else {}
|
|
346
|
+
skipped = 0
|
|
347
|
+
renamed = 0
|
|
348
|
+
downloaded = 0
|
|
349
|
+
|
|
350
|
+
with tqdm(
|
|
351
|
+
total=len(uid_sizes),
|
|
352
|
+
desc=display_name[:30],
|
|
353
|
+
unit="mail",
|
|
354
|
+
position=1,
|
|
355
|
+
leave=False,
|
|
356
|
+
) as folder_pbar:
|
|
357
|
+
for uid, remote_size in uid_sizes.items():
|
|
358
|
+
try:
|
|
359
|
+
existing_name = uid_index.get(uid)
|
|
360
|
+
if existing_name:
|
|
361
|
+
existing_file = folder_path / existing_name
|
|
362
|
+
if existing_file.is_file() and existing_file.stat().st_size == remote_size:
|
|
363
|
+
if args.update_existing_filenames:
|
|
364
|
+
with existing_file.open("rb") as fh:
|
|
365
|
+
msg_headers = header_parser.parse(fh)
|
|
366
|
+
base_name = build_base_filename(msg_headers, uid, args)
|
|
367
|
+
new_path = resolve_unique_path(
|
|
368
|
+
folder_path,
|
|
369
|
+
base_name,
|
|
370
|
+
ext=".eml",
|
|
371
|
+
current_path=existing_file,
|
|
372
|
+
)
|
|
373
|
+
if new_path != existing_file:
|
|
374
|
+
existing_file.rename(new_path)
|
|
375
|
+
uid_index[uid] = new_path.name
|
|
376
|
+
renamed += 1
|
|
377
|
+
logger.debug(
|
|
378
|
+
"Renamed UID %s: %s -> %s",
|
|
379
|
+
uid,
|
|
380
|
+
existing_file.name,
|
|
381
|
+
new_path.name,
|
|
382
|
+
)
|
|
383
|
+
else:
|
|
384
|
+
skipped += 1
|
|
385
|
+
else:
|
|
386
|
+
skipped += 1
|
|
387
|
+
logger.debug(
|
|
388
|
+
"Skipping UID %s (%s, %d bytes)",
|
|
389
|
+
uid,
|
|
390
|
+
existing_name,
|
|
391
|
+
remote_size,
|
|
392
|
+
)
|
|
393
|
+
continue
|
|
394
|
+
|
|
395
|
+
logger.debug(
|
|
396
|
+
"Size mismatch or missing file for UID %s (expected %d bytes). Re-downloading.",
|
|
397
|
+
uid,
|
|
398
|
+
remote_size,
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
res, msg_data = imap.uid("fetch", uid, "(RFC822)")
|
|
402
|
+
if res != "OK" or not msg_data or not isinstance(msg_data[0], tuple):
|
|
403
|
+
logger.warning("Failed to fetch UID %s in '%s'", uid, display_name)
|
|
404
|
+
continue
|
|
405
|
+
|
|
406
|
+
raw_email = msg_data[0][1]
|
|
407
|
+
msg = email.message_from_bytes(raw_email)
|
|
408
|
+
base_name = build_base_filename(msg, uid, args)
|
|
409
|
+
|
|
410
|
+
existing_path = (folder_path / existing_name) if existing_name else None
|
|
411
|
+
if existing_path and existing_path.is_file() and not args.update_existing_filenames:
|
|
412
|
+
target_file = existing_path
|
|
413
|
+
else:
|
|
414
|
+
target_file = resolve_unique_path(
|
|
415
|
+
folder_path, base_name, ext=".eml", current_path=existing_path
|
|
416
|
+
)
|
|
417
|
+
if existing_path and existing_path.is_file() and target_file != existing_path:
|
|
418
|
+
existing_path.unlink()
|
|
419
|
+
|
|
420
|
+
target_file.write_bytes(raw_email)
|
|
421
|
+
uid_index[uid] = target_file.name
|
|
422
|
+
downloaded += 1
|
|
423
|
+
logger.debug("Saved UID %s -> %s (%d bytes)", uid, target_file.name, len(raw_email))
|
|
424
|
+
finally:
|
|
425
|
+
folder_pbar.update(1)
|
|
426
|
+
total_pbar.update(1)
|
|
427
|
+
|
|
428
|
+
index_path.write_text(json.dumps(uid_index, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
429
|
+
|
|
430
|
+
local_eml_count = sum(1 for f in folder_path.iterdir() if f.is_file() and f.suffix == ".eml")
|
|
431
|
+
summary.append((display_name, server_count, local_eml_count, skipped, renamed, downloaded))
|
|
432
|
+
logger.info(
|
|
433
|
+
"Folder '%s': server=%d, local=%d (skipped=%d, renamed=%d, new=%d)",
|
|
434
|
+
display_name,
|
|
435
|
+
server_count,
|
|
436
|
+
local_eml_count,
|
|
437
|
+
skipped,
|
|
438
|
+
renamed,
|
|
439
|
+
downloaded,
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
logger.info("")
|
|
443
|
+
logger.info(
|
|
444
|
+
"%-36s | %7s | %7s | %7s | %7s | %7s | %s",
|
|
445
|
+
"Folder",
|
|
446
|
+
"Server",
|
|
447
|
+
"Local",
|
|
448
|
+
"Skipped",
|
|
449
|
+
"Renamed",
|
|
450
|
+
"New",
|
|
451
|
+
"Status",
|
|
452
|
+
)
|
|
453
|
+
logger.info("-" * 98)
|
|
454
|
+
for name, srv, loc, skp, ren, dwn in summary:
|
|
455
|
+
status_str = "OK" if srv == loc else ("LOCAL_EXTRA" if loc > srv else "MISMATCH")
|
|
456
|
+
logger.info(
|
|
457
|
+
"%-36s | %7d | %7d | %7d | %7d | %7d | %s",
|
|
458
|
+
name[:36],
|
|
459
|
+
srv,
|
|
460
|
+
loc,
|
|
461
|
+
skp,
|
|
462
|
+
ren,
|
|
463
|
+
dwn,
|
|
464
|
+
status_str,
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _add_common_arguments(target: argparse.ArgumentParser, *, is_subparser: bool = False) -> None:
|
|
469
|
+
"""Register common CLI options on either the root parser or a subparser."""
|
|
470
|
+
|
|
471
|
+
# Use SUPPRESS on subparsers so they do not overwrite values parsed by the root parser
|
|
472
|
+
def default(val: object) -> object:
|
|
473
|
+
return argparse.SUPPRESS if is_subparser else val
|
|
474
|
+
|
|
475
|
+
group = target.add_argument_group("common options")
|
|
476
|
+
group.add_argument("--host", default=default(None), help="IMAP server hostname (required)")
|
|
477
|
+
group.add_argument(
|
|
478
|
+
"--port",
|
|
479
|
+
type=int,
|
|
480
|
+
default=default(993),
|
|
481
|
+
help="IMAP SSL port (default: 993)",
|
|
482
|
+
)
|
|
483
|
+
group.add_argument("--user", default=default(None), help="IMAP username / email (required)")
|
|
484
|
+
pw_group = group.add_mutually_exclusive_group()
|
|
485
|
+
pw_group.add_argument("--password", default=default(None), help="IMAP password")
|
|
486
|
+
pw_group.add_argument(
|
|
487
|
+
"--password-file",
|
|
488
|
+
type=Path,
|
|
489
|
+
default=default(None),
|
|
490
|
+
help="Path to file containing IMAP password",
|
|
491
|
+
)
|
|
492
|
+
group.add_argument(
|
|
493
|
+
"-e",
|
|
494
|
+
"--exclude",
|
|
495
|
+
action="append",
|
|
496
|
+
default=default([]),
|
|
497
|
+
help=(
|
|
498
|
+
"Folder glob pattern to exclude, including its subfolders "
|
|
499
|
+
"(e.g. 'Trash' excludes Trash and all subfolders; 'Trash/*' excludes only subfolders; "
|
|
500
|
+
"can be specified multiple times)"
|
|
501
|
+
),
|
|
502
|
+
)
|
|
503
|
+
group.add_argument(
|
|
504
|
+
"-v",
|
|
505
|
+
"--verbose",
|
|
506
|
+
action="store_true",
|
|
507
|
+
default=default(False),
|
|
508
|
+
help="Enable debug logging",
|
|
509
|
+
)
|
|
510
|
+
group.add_argument(
|
|
511
|
+
"--version",
|
|
512
|
+
action="version",
|
|
513
|
+
version=f"%(prog)s {__version__}",
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
518
|
+
parser = argparse.ArgumentParser(
|
|
519
|
+
prog="mailbox-backup",
|
|
520
|
+
description="IMAP mailbox to .eml backup CLI.",
|
|
521
|
+
)
|
|
522
|
+
_add_common_arguments(parser, is_subparser=False)
|
|
523
|
+
|
|
524
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
525
|
+
|
|
526
|
+
p_list = subparsers.add_parser("list", help="List remote folders and message counts")
|
|
527
|
+
_add_common_arguments(p_list, is_subparser=True)
|
|
528
|
+
|
|
529
|
+
p_backup = subparsers.add_parser("backup", help="Backup mailbox to .eml files")
|
|
530
|
+
_add_common_arguments(p_backup, is_subparser=True)
|
|
531
|
+
p_backup.add_argument("--out", type=Path, required=True, help="Output directory")
|
|
532
|
+
p_backup.add_argument(
|
|
533
|
+
"--format",
|
|
534
|
+
default=DEFAULT_FILENAME_TEMPLATE,
|
|
535
|
+
help=(
|
|
536
|
+
"Filename template without extension. "
|
|
537
|
+
"Placeholders: {date}, {time}, {sender}, {recipient}, {subject}, {uid} "
|
|
538
|
+
"(default: %(default)s)"
|
|
539
|
+
),
|
|
540
|
+
)
|
|
541
|
+
p_backup.add_argument(
|
|
542
|
+
"--date-format",
|
|
543
|
+
default=DEFAULT_DATE_FORMAT,
|
|
544
|
+
help="strftime format for {date} (default: %(default)s)",
|
|
545
|
+
)
|
|
546
|
+
p_backup.add_argument(
|
|
547
|
+
"--time-format",
|
|
548
|
+
default=DEFAULT_TIME_FORMAT,
|
|
549
|
+
help="strftime format for {time} (default: %(default)s)",
|
|
550
|
+
)
|
|
551
|
+
p_backup.add_argument(
|
|
552
|
+
"--update-existing-filenames",
|
|
553
|
+
action="store_true",
|
|
554
|
+
help="Rename already downloaded .eml files locally if they do not match the current --format",
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
return parser
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def main() -> None:
|
|
561
|
+
parser = build_parser()
|
|
562
|
+
args = parser.parse_args()
|
|
563
|
+
|
|
564
|
+
if not args.host or not args.user:
|
|
565
|
+
parser.error("the following arguments are required: --host, --user")
|
|
566
|
+
|
|
567
|
+
log_format = "%(levelname)s: %(message)s" if args.verbose else "%(message)s"
|
|
568
|
+
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format=log_format)
|
|
569
|
+
logger.info("mailbox-backup %s", __version__)
|
|
570
|
+
|
|
571
|
+
password = load_password(args)
|
|
572
|
+
|
|
573
|
+
with imaplib.IMAP4_SSL(args.host, args.port) as imap:
|
|
574
|
+
imap.login(args.user, password)
|
|
575
|
+
logger.debug("Connected to %s:%d as %s", args.host, args.port, args.user)
|
|
576
|
+
|
|
577
|
+
if args.command == "list":
|
|
578
|
+
cmd_list(imap, args.exclude)
|
|
579
|
+
elif args.command == "backup":
|
|
580
|
+
cmd_backup(imap, args)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
if __name__ == "__main__":
|
|
584
|
+
main()
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mailbox-backup
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Create a local copy of your e-mail account via IMAP
|
|
5
|
+
Keywords: imap,email,backup,eml,archive,mailbox,cli
|
|
6
|
+
Author: Robert Nitsch
|
|
7
|
+
Author-email: Robert Nitsch <mail@robertnitsch.de>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
20
|
+
Classifier: Topic :: Communications :: Email
|
|
21
|
+
Classifier: Topic :: System :: Archiving :: Backup
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Requires-Dist: tqdm>=4.70.1
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# mailbox-backup
|
|
28
|
+
|
|
29
|
+
[](https://opensource.org/licenses/MIT)
|
|
30
|
+
[](https://www.python.org/)
|
|
31
|
+
[](https://github.com/astral-sh/uv)
|
|
32
|
+
[](https://github.com/astral-sh/ruff)
|
|
33
|
+
|
|
34
|
+
A fast, reliable CLI tool to back up entire IMAP mailboxes to individual `.eml` (RFC 822) files while preserving the
|
|
35
|
+
remote folder hierarchy.
|
|
36
|
+
|
|
37
|
+
## Features
|
|
38
|
+
|
|
39
|
+
- **Individual `.eml` files:** Saves every email as a standard `.eml` file in a mirrored local directory structure.
|
|
40
|
+
- **Incremental & Size-Verified:** Tracks downloaded messages per folder via `.imap_index.json`. Existing emails are
|
|
41
|
+
only skipped if both the file exists and its exact byte size matches the server's `RFC822.SIZE`.
|
|
42
|
+
- **Customizable Filenames:** Configure filename templates, date/time formats, and field truncation (e.g.,
|
|
43
|
+
`{date}-{time}_{subject:.50}`).
|
|
44
|
+
- **Safe Cross-Platform Naming:** Automatically sanitizes filenames, handles duplicates (`-2`, `-3`, ...), and respects
|
|
45
|
+
both Linux/macOS 255-byte filename limits and Windows `MAX_PATH`.
|
|
46
|
+
- **In-Place Renaming:** Change your naming template later and rename existing local files via
|
|
47
|
+
`--update-existing-filenames` without re-downloading.
|
|
48
|
+
- **Transparent Folder Exclusions:** Exclude folders using glob patterns.
|
|
49
|
+
- **Progress & Verification:** Dual `tqdm` progress bars (total + current folder) and a final verification table
|
|
50
|
+
comparing server counts against local `.eml` counts (`OK`, `LOCAL_EXTRA`, `MISMATCH`).
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
Requires Python 3.12+ and [`uv`](https://github.com/astral-sh/uv):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
git clone https://github.com/rsnitsch/mailbox-backup.git
|
|
58
|
+
cd mailbox-backup
|
|
59
|
+
uv sync
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
### List remote folders and message counts
|
|
65
|
+
|
|
66
|
+
Inspect all available remote folders (sorted alphabetically) and their message counts before running a backup:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv run mailbox-backup list \
|
|
70
|
+
--host imap.example.com \
|
|
71
|
+
--user user@example.com \
|
|
72
|
+
--password-file ./password.txt
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Back up a mailbox
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
uv run mailbox-backup backup \
|
|
79
|
+
--host imap.example.com \
|
|
80
|
+
--user user@example.com \
|
|
81
|
+
--password-file ./password.txt \
|
|
82
|
+
--out ./backup
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
If neither `--password` nor `--password-file` is provided, the tool will securely prompt for the password interactively.
|
|
86
|
+
|
|
87
|
+
### Custom filename format & exclusions
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
uv run mailbox-backup backup \
|
|
91
|
+
--host imap.example.com \
|
|
92
|
+
--user user@example.com \
|
|
93
|
+
--password-file ./password.txt \
|
|
94
|
+
--out ./backup \
|
|
95
|
+
--format "{date}-{time}_{sender}_{subject:.60}_{uid}" \
|
|
96
|
+
--date-format "%Y-%m-%d" \
|
|
97
|
+
--time-format "%H-%M-%S" \
|
|
98
|
+
-e "Trash" \
|
|
99
|
+
-e "Spam" \
|
|
100
|
+
-e "Archive/2020/*"
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Update existing filenames locally
|
|
104
|
+
|
|
105
|
+
If you change `--format`, `--date-format`, or `--time-format` after an initial backup, pass
|
|
106
|
+
`--update-existing-filenames` to rename already downloaded `.eml` files locally without re-downloading them:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
uv run mailbox-backup backup \
|
|
110
|
+
--host imap.example.com \
|
|
111
|
+
--user user@example.com \
|
|
112
|
+
--password-file ./password.txt \
|
|
113
|
+
--out ./backup \
|
|
114
|
+
--format "{date}_{time}_{subject:.50}" \
|
|
115
|
+
--update-existing-filenames
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## CLI Reference
|
|
119
|
+
|
|
120
|
+
### Common Options (`list` & `backup`)
|
|
121
|
+
|
|
122
|
+
| Option | Description |
|
|
123
|
+
| :------------------------ | :------------------------------------------- |
|
|
124
|
+
| `--host HOST` | IMAP server hostname (required) |
|
|
125
|
+
| `--port PORT` | IMAP SSL port (default: `993`) |
|
|
126
|
+
| `--user USER` | IMAP username / email address (required) |
|
|
127
|
+
| `--password PASSWORD` | IMAP password |
|
|
128
|
+
| `--password-file PATH` | Path to a file containing the IMAP password |
|
|
129
|
+
| `-e`, `--exclude PATTERN` | Glob pattern to exclude folders (repeatable) |
|
|
130
|
+
| `-v`, `--verbose` | Enable debug logging |
|
|
131
|
+
|
|
132
|
+
### `backup` Options
|
|
133
|
+
|
|
134
|
+
| Option | Default | Description |
|
|
135
|
+
| :---------------------------- | :---------------------------- | :----------------------------------------------------------------- |
|
|
136
|
+
| `--out PATH` | *(required)* | Local target directory for the backup |
|
|
137
|
+
| `--format TEMPLATE` | `{date}-{time}_{subject:.50}` | Filename template without `.eml` extension |
|
|
138
|
+
| `--date-format FMT` | `%Y%m%d` | `strftime` format for `{date}` |
|
|
139
|
+
| `--time-format FMT` | `%H%M%S` | `strftime` format for `{time}` |
|
|
140
|
+
| `--update-existing-filenames` | `false` | Rename existing local `.eml` files to match the current `--format` |
|
|
141
|
+
|
|
142
|
+
**Available `--format` placeholders:** `{date}`, `{time}`, `{sender}`, `{recipient}`, `{subject}`, `{uid}`\
|
|
143
|
+
*(Use Python format specifiers like `{subject:.50}` to limit field length.)*
|
|
144
|
+
|
|
145
|
+
### Exclusion Rules (`-e` / `--exclude`)
|
|
146
|
+
|
|
147
|
+
Exclusions follow `.gitignore` / `tar` semantics and work independently of the IMAP server's hierarchy delimiter (`/` or
|
|
148
|
+
`.`):
|
|
149
|
+
|
|
150
|
+
- `-e Trash` — Excludes `Trash` **and all of its subfolders** (`Trash/A`, `Trash/A/B`).
|
|
151
|
+
- `-e "Trash/*"` — Excludes **only the subfolders** of `Trash`, keeping `Trash` itself.
|
|
152
|
+
- `-e "*Spam*"` — Excludes any folder containing `Spam` and all of its subfolders.
|
|
153
|
+
|
|
154
|
+
## Verification Output
|
|
155
|
+
|
|
156
|
+
At the end of every backup run, `mailbox-backup` prints a summary table:
|
|
157
|
+
|
|
158
|
+
```text
|
|
159
|
+
Folder | Server | Local | Skipped | Renamed | New | Status
|
|
160
|
+
--------------------------------------------------------------------------------------------------
|
|
161
|
+
INBOX | 142 | 142 | 140 | 0 | 2 | OK
|
|
162
|
+
Sent | 58 | 60 | 58 | 0 | 0 | LOCAL_EXTRA
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
- **`OK`**: Server count and local `.eml` count match.
|
|
166
|
+
- **`LOCAL_EXTRA`**: More `.eml` files exist locally than on the server (e.g., messages deleted remotely remain archived
|
|
167
|
+
locally).
|
|
168
|
+
- **`MISMATCH`**: Fewer `.eml` files exist locally than on the server (check warnings / rerun).
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
This project is licensed under the [MIT License](LICENSE).
|
|
173
|
+
|
|
174
|
+
<!--
|
|
175
|
+
This README was formatted with:
|
|
176
|
+
uvx --with mdformat-gfm --with mdformat-dollarmath mdformat --wrap 120 README.md
|
|
177
|
+
-->
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
mailbox_backup/__init__.py,sha256=EiEBiZb_r62FDqIwZbAecDMWrgnrzCTnfDbSYn6BHao,22003
|
|
2
|
+
mailbox_backup-0.1.0.dist-info/licenses/LICENSE,sha256=oCGPLcb33EE5_l1dEb2tK8-X9skiPyyGDjCXt2Or--c,1070
|
|
3
|
+
mailbox_backup-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
|
|
4
|
+
mailbox_backup-0.1.0.dist-info/entry_points.txt,sha256=NTMZIBI8z03XT8Q77JgCwq-v6EDJEnLjhZWqImITx48,56
|
|
5
|
+
mailbox_backup-0.1.0.dist-info/METADATA,sha256=KXyYL7mD_jzRdfop3qMf42VoMJDWFfau9YP8qASz-JY,7725
|
|
6
|
+
mailbox_backup-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Robert Nitsch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|