-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimapsynchronizer.py
More file actions
2777 lines (2453 loc) · 117 KB
/
Copy pathimapsynchronizer.py
File metadata and controls
2777 lines (2453 loc) · 117 KB
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
IMAP Synchronizer — interactive IMAP migration toolkit.
Cross-platform (Windows / macOS / Linux) tool to inspect, migrate and
verify IMAP mailboxes. Runs an interactive, colorized menu:
1. List folders and message counts of an account (exportable to TXT).
2. Copy messages from a source account into a destination account,
under _IMAP-Synchronizer/<user>_<host>/..., resumable and duplicate-safe.
3. Compare two accounts folder-by-folder / message-by-message.
Only third-party dependency is 'rich', which is installed automatically
on first run. Everything else is the Python standard library.
Originally based on imapcopy (c) 2013 Christoph Heer (BSD license);
rewritten as an interactive tool.
"""
import sys
MIN_PYTHON = (3, 8)
if sys.version_info < MIN_PYTHON:
sys.stderr.write(
"IMAP Synchronizer requires Python %d.%d or later (you are running %s).\n"
% (MIN_PYTHON[0], MIN_PYTHON[1], sys.version.split()[0])
)
sys.exit(1)
def _ensure_dependencies():
"""Install missing third-party packages (rich) on first run."""
try:
import rich # noqa: F401
return
except ImportError:
pass
import platform
import subprocess
import importlib
print("First run: installing required package 'rich' ...")
try:
import pip # noqa: F401
except ImportError:
subprocess.call([sys.executable, "-m", "ensurepip", "--upgrade"])
commands = [
[sys.executable, "-m", "pip", "install", "--disable-pip-version-check", "rich"],
[sys.executable, "-m", "pip", "install", "--user",
"--disable-pip-version-check", "rich"],
# Debian 12+ / Ubuntu 23.04+ mark the system Python as
# "externally managed" (PEP 668) and refuse both commands above;
# a per-user install with this override is the standard workaround.
[sys.executable, "-m", "pip", "install", "--user",
"--break-system-packages", "--disable-pip-version-check", "rich"],
]
for cmd in commands:
if subprocess.call(cmd) == 0:
importlib.invalidate_caches()
try:
import rich # noqa: F401
print("Dependency 'rich' installed successfully.\n")
return
except ImportError:
continue
system = platform.system()
print("\nCould not install 'rich' automatically. Please install it manually:")
if system == "Darwin":
print(" brew install python3 (if Python came from Homebrew)")
print(" python3 -m pip install rich")
elif system == "Windows":
print(" python -m pip install rich")
else:
print(" sudo apt install python3-rich (Debian / Ubuntu)")
print(" sudo dnf install python3-rich (Fedora)")
print(" python3 -m pip install --user rich (other distributions)")
sys.exit(1)
_ensure_dependencies()
import os # noqa: E402
import re # noqa: E402
import csv # noqa: E402
import ssl # noqa: E402
import json # noqa: E402
import base64 # noqa: E402
import socket # noqa: E402
import hashlib # noqa: E402
import imaplib # noqa: E402
import logging # noqa: E402
from pathlib import Path # noqa: E402
from datetime import datetime, timedelta # noqa: E402
from collections import Counter # noqa: E402
from dataclasses import dataclass, field # noqa: E402
from email.parser import BytesHeaderParser # noqa: E402
from email.message import EmailMessage # noqa: E402
from email.utils import formatdate, make_msgid # noqa: E402
from html import escape as html_escape # noqa: E402
from rich import box # noqa: E402
from rich.markup import escape as rich_escape # noqa: E402
from rich.panel import Panel # noqa: E402
from rich.table import Table # noqa: E402
from rich.console import Console # noqa: E402
from rich.prompt import Prompt, IntPrompt, Confirm # noqa: E402
from rich.progress import ( # noqa: E402
Progress, SpinnerColumn, BarColumn, TextColumn,
TaskProgressColumn, TimeElapsedColumn,
)
APP_NAME = "IMAP Synchronizer"
APP_VERSION = "2.1"
APP_OWNER = "function0xMarki"
APP_REPO_URL = "https://github.com/function0xMarki/IMAP-Synchronizer"
MIGRATION_ROOT = "_IMAP-Synchronizer"
# Sandbox roots used by older versions — still excluded when the source and
# destination are the same account, so re-runs never copy them into themselves.
LEGACY_MIGRATION_ROOTS = ("_IMAP_SYNC",)
SCRIPT_DIR = Path(__file__).resolve().parent
PROFILES_FILE = SCRIPT_DIR / "imapsynchronizer_profiles.json"
REPORTS_DIR = SCRIPT_DIR / "reports"
LOGS_DIR = SCRIPT_DIR / "logs"
def ensure_reports_dir() -> Path:
"""All exported TXT reports go into reports/ ."""
REPORTS_DIR.mkdir(exist_ok=True)
return REPORTS_DIR
def ensure_logs_dir() -> Path:
"""Session error logs and detailed migration logs go into logs/ ."""
LOGS_DIR.mkdir(exist_ok=True)
return LOGS_DIR
# Large mailboxes produce long untagged responses; the imaplib default
# (1 MB) can be exceeded by FETCH responses with big header sets.
imaplib._MAXLINE = 10 * 1024 * 1024
socket.setdefaulttimeout(60)
# Legacy Windows consoles default to a codepage (cp1252/cp850) that cannot
# represent the box-drawing characters used in folder trees.
if sys.platform == "win32":
os.system("") # enable VT / ANSI processing in the console
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, OSError):
pass
console = Console(highlight=False)
log = logging.getLogger("imapsynchronizer")
log.setLevel(logging.DEBUG)
from rich.logging import RichHandler # noqa: E402
_console_log = RichHandler(console=console, show_time=False, show_path=False)
_console_log.setLevel(logging.WARNING)
log.addHandler(_console_log)
_error_log_handler = None
def setup_error_log():
"""Open one session error log per program start, under logs/.
Records every WARNING and ERROR of the whole session — connection
failures, per-message/per-folder errors, and transient errors that
were retried and resolved — so an admin can debug afterwards."""
global _error_log_handler
try:
path = (ensure_logs_dir()
/ f"imapsynchronizer_{datetime.now():%Y%m%d_%H%M%S}.log")
with open(path, "w", encoding="utf-8") as fh:
fh.write(
f"# {APP_NAME} v{APP_VERSION} — session error log\n"
f"# Started : {datetime.now():%Y-%m-%d %H:%M:%S}\n"
f"# Python : {sys.version.split()[0]} on {sys.platform}\n"
f"# Mode : {' '.join(sys.argv[1:]) or 'interactive menu'}\n"
"# Contains: warnings and errors, including transient "
"errors that were retried and resolved\n")
handler = logging.FileHandler(path, mode="a", encoding="utf-8")
except OSError as exc:
console.print(f"[yellow]Could not create the session error log "
f"({exc}) — continuing without it.[/yellow]")
return None
handler.setLevel(logging.WARNING)
handler.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-7s %(message)s"))
log.addHandler(handler)
_error_log_handler = handler
return path
def close_error_log(exit_code: int):
global _error_log_handler
if _error_log_handler is None:
return
path = _error_log_handler.baseFilename
log.removeHandler(_error_log_handler)
_error_log_handler.close()
_error_log_handler = None
try:
with open(path, "a", encoding="utf-8") as fh:
fh.write(f"# Ended : {datetime.now():%Y-%m-%d %H:%M:%S} "
f"(exit code {exit_code})\n")
except OSError:
pass
# --------------------------------------------------------------------------
# IMAP modified UTF-7 (RFC 3501 section 5.1.3) folder-name codec
# --------------------------------------------------------------------------
def imap_utf7_encode(text: str) -> str:
"""Encode a folder name to IMAP modified UTF-7 (ASCII-safe)."""
out, buf = [], []
def flush():
if buf:
b64 = base64.b64encode("".join(buf).encode("utf-16-be"))
out.append("&" + b64.decode("ascii").rstrip("=").replace("/", ",") + "-")
buf.clear()
for ch in text:
if 0x20 <= ord(ch) <= 0x7E:
flush()
out.append("&-" if ch == "&" else ch)
else:
buf.append(ch)
flush()
return "".join(out)
def imap_utf7_decode(text: str) -> str:
"""Decode an IMAP modified UTF-7 folder name to a normal string."""
out, i = [], 0
while i < len(text):
ch = text[i]
if ch != "&":
out.append(ch)
i += 1
continue
end = text.find("-", i + 1)
if end == -1:
out.append(text[i:])
break
chunk = text[i + 1:end]
if chunk == "":
out.append("&")
else:
b64 = chunk.replace(",", "/")
b64 += "=" * ((4 - len(b64) % 4) % 4)
try:
out.append(base64.b64decode(b64).decode("utf-16-be"))
except Exception:
out.append(text[i:end + 1])
i = end + 1
return "".join(out)
def quote_mailbox(raw: str) -> str:
"""Quote a mailbox name for use in an IMAP command (imaplib does not)."""
return '"' + raw.replace("\\", "\\\\").replace('"', '\\"') + '"'
def sanitize_component(part: str, delimiter) -> str:
"""Make a folder-path component safe for the destination server."""
part = "".join(ch for ch in part if ord(ch) >= 32)
if delimiter:
part = part.replace(delimiter, "_")
part = part.strip()
return part or "_"
def sanitize_filename(name: str) -> str:
return re.sub(r"[^\w.@-]+", "_", name).strip("._") or "account"
def strip_surrounding_quotes(value: str) -> str:
"""Remove one pair of matching surrounding quotes, if present.
Lets users paste passwords wrapped in quotes (to protect leading or
trailing spaces) without the quotes becoming part of the password.
Everything typed between them — commas, semicolons, ñ, symbols — is
taken literally.
"""
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
return value[1:-1]
return value
def is_ascii(text: str) -> bool:
return all(ord(ch) < 128 for ch in text)
def normalize_host(text: str):
"""Clean a server address the way users actually paste it.
Accepts 'imap://host', 'imaps://host/', 'host:993', stray spaces or a
trailing slash; returns (host, port_or_None). IPv6 literals are left
untouched."""
host = (text or "").strip().rstrip("/")
for prefix in ("imaps://", "imap://"):
if host.lower().startswith(prefix):
host = host[len(prefix):]
break
port = None
if host.count(":") == 1:
candidate, maybe_port = host.rsplit(":", 1)
if maybe_port.isdigit():
host, port = candidate, int(maybe_port)
return host, port
def message_key(header_bytes: bytes) -> str:
"""Stable identity of a message: Message-ID, or a hash of its headers."""
msg = BytesHeaderParser().parsebytes(header_bytes or b"")
mid = (msg.get("Message-ID") or "").strip()
if mid:
return "mid:" + mid
digest = hashlib.sha1(b"".join((header_bytes or b"").split())).hexdigest()
return "hdr:" + digest
def _chunks(seq, size):
for i in range(0, len(seq), size):
yield seq[i:i + size]
def _flatten_response(data) -> bytes:
parts = []
for item in data or []:
if isinstance(item, tuple):
parts.extend(p for p in item if isinstance(p, bytes))
elif isinstance(item, bytes):
parts.append(item)
return b" ".join(parts)
def _iter_fetch_literals(data):
"""Yield (info, literal) pairs from an imaplib FETCH response.
Servers may place attributes (e.g. UID) before or after the literal;
imaplib delivers the part after it as a separate bytes element, so all
fragments of one message record are merged into a single info line.
"""
info, literal = None, None
for item in data or []:
if isinstance(item, tuple) and len(item) >= 2:
if info is not None:
yield info, literal
info, literal = item[0], item[1]
elif isinstance(item, bytes) and info is not None:
info += b" " + item
if info is not None:
yield info, literal
# --------------------------------------------------------------------------
# IMAP session
# --------------------------------------------------------------------------
class ImapError(Exception):
pass
class MigrationAborted(ImapError):
"""Raised when too many consecutive messages fail — the connection is
almost certainly dead and continuing would hang for hours on timeouts."""
# Flags every IMAP server must accept in APPEND (RFC 3501). Anything else
# (keywords like $Forwarded, Gmail labels) may be rejected by strict servers.
STANDARD_FLAGS = ("\\seen", "\\answered", "\\flagged", "\\draft", "\\deleted")
def append_flag_attempts(flags):
"""Flag sets to try for APPEND, from most to least faithful.
Starts with the original flags; falls back to the standard subset and
finally to no flags, so a server that rejects custom keywords still
receives the message (losing only the keyword, which is logged)."""
attempts = [flags]
if flags:
std = " ".join(t for t in flags.split() if t.lower() in STANDARD_FLAGS)
for alt in (std or None, None):
if alt not in attempts:
attempts.append(alt)
return attempts
@dataclass
class Account:
host: str
port: int
user: str
password: str = field(repr=False, default="")
@property
def label(self) -> str:
return f"{self.user} @ {self.host}:{self.port}"
@dataclass
class Folder:
raw: str # raw (modified UTF-7) full name, as used on the wire
name: str # decoded, human-readable full name
delimiter: str # hierarchy delimiter (may be None on odd servers)
parts: tuple # decoded path components
selectable: bool
flags: str = "" # LIST flags, e.g. "\\HasChildren \\All"
def has_flag(self, flag: str) -> bool:
return flag.lower() in self.flags.lower().split()
_LIST_LINE_RE = re.compile(
r'^\((?P<flags>[^)]*)\)\s+(?:"(?P<delim>(?:\\.|[^"\\])*)"|NIL)\s+(?P<name>.*)$',
re.DOTALL,
)
_LIST_PREFIX_RE = re.compile(
r'^\((?P<flags>[^)]*)\)\s+(?:"(?P<delim>(?:\\.|[^"\\])*)"|NIL)\s+'
)
def _unescape_quoted(value: str) -> str:
return value.replace('\\"', '"').replace("\\\\", "\\")
def parse_list_entry(entry):
"""Parse one imaplib LIST response entry.
Returns (flags, delimiter, raw_name) or None if unparseable.
Handles quoted names, unquoted names and literal continuations
(imaplib delivers literals as (prefix, name) tuples).
"""
if entry is None:
return None
if isinstance(entry, tuple):
prefix = entry[0].decode("ascii", "replace")
m = _LIST_PREFIX_RE.match(prefix)
if not m:
return None
raw_name = entry[1].decode("ascii", "replace")
else:
line = entry.decode("ascii", "replace")
if not line.strip():
return None
m = _LIST_LINE_RE.match(line)
if not m:
return None
raw_name = m.group("name").strip()
if raw_name.startswith('"') and raw_name.endswith('"') and len(raw_name) >= 2:
raw_name = _unescape_quoted(raw_name[1:-1])
flags = m.group("flags") or ""
delim = m.group("delim")
if delim is not None:
delim = _unescape_quoted(delim)
return flags, delim, raw_name
class ImapSession:
def __init__(self, account: Account, role: str = "server"):
self.account = account
self.role = role
self.conn = None
self.delimiter = "/"
self.allow_insecure_ssl = True
self._selected = None # (raw_name, readonly) currently selected
self._known_raw = None # set of raw folder names known to exist
# -- connection -------------------------------------------------------
def connect(self):
acct = self.account
ctx = ssl.create_default_context()
if self.allow_insecure_ssl:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
if acct.port == 993:
conn = imaplib.IMAP4_SSL(acct.host, acct.port, ssl_context=ctx)
else:
conn = imaplib.IMAP4(acct.host, acct.port)
if "STARTTLS" in conn.capabilities:
conn.starttls(ctx)
else:
log.warning("%s: connection to %s:%s is NOT encrypted",
self.role, acct.host, acct.port)
# IMAP LOGIN only carries ASCII. Credentials with ñ, accents or any
# other non-ASCII characters are sent via AUTHENTICATE PLAIN, which
# is base64-encoded UTF-8 and accepts every character.
if is_ascii(acct.user) and is_ascii(acct.password):
conn.login(acct.user, acct.password)
else:
def _auth_plain(_challenge):
return (b"\0" + acct.user.encode("utf-8")
+ b"\0" + acct.password.encode("utf-8"))
try:
conn.authenticate("PLAIN", _auth_plain)
except imaplib.IMAP4.error as exc:
raise ImapError(
"The password/username contains non-ASCII characters and "
"the server rejected AUTH PLAIN (%s). Plain IMAP LOGIN "
"cannot transmit those characters." % exc)
self.conn = conn
self._detect_delimiter()
def _detect_delimiter(self):
typ, data = self.conn.list('""', '*')
if typ == "OK":
for entry in data:
parsed = parse_list_entry(entry)
if parsed and parsed[1]:
self.delimiter = parsed[1]
return
def reconnect(self):
try:
self.conn.shutdown()
except Exception:
pass
log.warning("%s: connection lost, reconnecting to %s",
self.role, self.account.host)
self.connect()
if self._selected:
raw, readonly = self._selected
self.select_folder(raw, readonly=readonly)
def logout(self):
if self.conn is None:
return
try:
if self.conn.state == "SELECTED":
self.conn.close()
self.conn.logout()
except Exception:
pass
self.conn = None
def _retry(self, fn):
"""Run fn(); on a dropped connection, reconnect once and retry."""
try:
return fn()
except (imaplib.IMAP4.abort, ssl.SSLError, OSError) as exc:
log.warning("%s: retrying after connection error: %s", self.role, exc)
self.reconnect()
result = fn()
log.warning("%s: operation succeeded after reconnect — "
"transient error resolved", self.role)
return result
# -- folders ----------------------------------------------------------
def list_folders(self):
typ, data = self._retry(lambda: self.conn.list())
if typ != "OK":
raise ImapError(f"LIST failed on {self.account.host}: "
f"{_flatten_response(data).decode('ascii', 'replace')}")
folders = []
for entry in data:
if not entry:
continue
parsed = parse_list_entry(entry)
if parsed is None:
log.warning("%s: unparseable LIST entry skipped: %r", self.role, entry)
continue
flags, delim, raw = parsed
delim = delim or self.delimiter
name = imap_utf7_decode(raw)
parts = tuple(name.split(delim)) if delim else (name,)
selectable = "\\noselect" not in flags.lower()
folders.append(Folder(raw=raw, name=name, delimiter=delim,
parts=parts, selectable=selectable,
flags=flags))
folders.sort(key=lambda f: tuple(p.lower() for p in f.parts))
self._known_raw = {f.raw for f in folders}
return folders
def message_count(self, folder: Folder):
if not folder.selectable:
return None
typ, data = self._retry(
lambda: self.conn.status(quote_mailbox(folder.raw), "(MESSAGES)"))
if typ == "OK":
m = re.search(rb"MESSAGES\s+(\d+)", _flatten_response(data))
if m:
return int(m.group(1))
# Some servers refuse STATUS; fall back to EXAMINE.
try:
return self.select_folder(folder.raw, readonly=True)
except ImapError:
return None
def select_folder(self, raw: str, readonly: bool = True) -> int:
typ, data = self._retry(
lambda: self.conn.select(quote_mailbox(raw), readonly=readonly))
if typ != "OK":
raise ImapError(
f"Cannot open folder '{imap_utf7_decode(raw)}' on "
f"{self.account.host}: "
f"{_flatten_response(data).decode('ascii', 'replace')}")
self._selected = (raw, readonly)
try:
return int(data[0])
except (TypeError, ValueError, IndexError):
return 0
def ensure_path(self, parts) -> str:
"""Create folder path (and ancestors) on this server; return raw name."""
if self._known_raw is None:
self.list_folders()
raw_parts = [imap_utf7_encode(p) for p in parts]
raw = ""
for i in range(1, len(raw_parts) + 1):
raw = self.delimiter.join(raw_parts[:i])
if raw in self._known_raw or raw.upper() == "INBOX":
continue
typ, data = self._retry(lambda r=raw: self.conn.create(quote_mailbox(r)))
if typ != "OK":
detail = _flatten_response(data).decode("ascii", "replace")
# Tolerate only a real "already exists" answer. A plain
# 'exist' substring is NOT enough: Dovecot's namespace
# rejection says "nonexistent namespace", which must fail
# here so the INBOX-prefix fallback can kick in.
compact = detail.lower().replace(" ", "")
if ("alreadyexists" not in compact
and "fileexists" not in compact):
raise ImapError(
f"Cannot create folder '{' / '.join(parts[:i])}' on "
f"{self.account.host}: {detail}")
try:
self.conn.subscribe(quote_mailbox(raw))
except Exception:
pass
self._known_raw.add(raw)
return raw
# -- messages ---------------------------------------------------------
def search_uids(self, raw: str, criteria=None):
"""Return the UID list of messages matching criteria (default: ALL)."""
self.select_folder(raw, readonly=True)
typ, data = self._retry(
lambda: self.conn.uid("SEARCH", criteria or "ALL"))
if typ != "OK":
raise ImapError(f"SEARCH failed in '{imap_utf7_decode(raw)}'")
return data[0].split() if data and data[0] else []
def fetch_message_keys(self, raw: str, criteria=None, on_progress=None):
"""Return [(uid, key), ...] for messages matching criteria (default ALL)."""
uids = self.search_uids(raw, criteria)
pairs = []
for chunk in _chunks(uids, 400):
uidset = b",".join(chunk).decode("ascii")
def do_fetch(us=uidset):
return self.conn.uid(
"FETCH", us,
"(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID FROM TO DATE SUBJECT)])")
typ, fdata = self._retry(do_fetch)
if typ != "OK":
raise ImapError(f"FETCH failed in '{imap_utf7_decode(raw)}'")
for info, literal in _iter_fetch_literals(fdata):
m = re.search(rb"UID (\d+)", info)
if not m:
continue
pairs.append((m.group(1).decode("ascii"), message_key(literal)))
if on_progress:
on_progress(len(chunk))
return pairs
def fetch_full_message(self, uid: str):
"""Return (flags, internaldate, rfc822_bytes) or None."""
def do_fetch():
return self.conn.uid("FETCH", uid, "(FLAGS INTERNALDATE BODY.PEEK[])")
typ, data = self._retry(do_fetch)
if typ != "OK" or not data:
return None
# Use only the record that carries the message literal; servers may
# interleave unsolicited untagged responses (flag changes seen by
# other sessions) whose FLAGS must not be mistaken for this message's.
meta, body = b"", None
for info, literal in _iter_fetch_literals(data):
if literal is not None and b"BODY[" in info.upper():
meta, body = info, literal
if body is None:
return None
flags = None
m = re.search(rb"FLAGS \(([^)]*)\)", meta)
if m:
tokens = [t for t in m.group(1).decode("ascii", "replace").split()
if t.lower() != "\\recent"]
if tokens:
flags = " ".join(tokens)
internaldate = None
m = re.search(rb'INTERNALDATE "([^"]+)"', meta)
if m:
internaldate = m.group(1).decode("ascii", "replace")
return flags, internaldate, body
def append_message(self, raw: str, flags, internaldate, body: bytes):
date_param = '"%s"' % internaldate if internaldate else None
detail = ""
for attempt, fl in enumerate(append_flag_attempts(flags)):
def do_append(f=fl):
return self.conn.append(quote_mailbox(raw), f, date_param, body)
typ, data = self._retry(do_append)
if typ == "OK":
if attempt:
log.warning("%s: server refused flags %r — message stored "
"with %r instead",
imap_utf7_decode(raw), flags, fl)
return
detail = _flatten_response(data).decode("ascii", "replace")
raise ImapError(
f"APPEND to '{imap_utf7_decode(raw)}' failed: {detail}")
# --------------------------------------------------------------------------
# Profiles (host/port/user only — passwords are never stored)
# --------------------------------------------------------------------------
def load_profiles():
try:
with open(PROFILES_FILE, "r", encoding="utf-8") as fh:
data = json.load(fh)
except (OSError, json.JSONDecodeError):
return []
profiles = []
for p in data.get("profiles", []):
if not (isinstance(p, dict) and p.get("host") and p.get("user")):
continue
try:
p["port"] = int(p.get("port", 993))
except (TypeError, ValueError):
p["port"] = 993 # hand-edited file with a broken port
profiles.append(p)
return profiles
def save_profiles(profiles):
try:
with open(PROFILES_FILE, "w", encoding="utf-8") as fh:
json.dump({"profiles": profiles}, fh, indent=2, ensure_ascii=False)
except OSError as exc:
console.print(f"[yellow]Could not save profiles: {exc}[/yellow]")
def maybe_save_profile(account: Account):
profiles = load_profiles()
for p in profiles:
if (p["host"], int(p.get("port", 993)), p["user"]) == \
(account.host, account.port, account.user):
return
if Confirm.ask(" Save this connection as a profile "
"(the password is [bold]never[/bold] stored)?", default=True):
name = Prompt.ask(" Profile name", default=account.user)
profiles.append({"name": name, "host": account.host,
"port": account.port, "user": account.user})
save_profiles(profiles)
console.print(f" [green]Profile '{name}' saved.[/green]")
# --------------------------------------------------------------------------
# Interactive prompts
# --------------------------------------------------------------------------
def prompt_account(title: str) -> Account:
console.print()
console.rule(f"[bold cyan]{title}[/bold cyan]", style="cyan")
profiles = load_profiles()
chosen = None
if profiles:
table = Table(box=box.SIMPLE, show_edge=False, pad_edge=False)
table.add_column("#", style="cyan", justify="right")
table.add_column("Profile")
table.add_column("User")
table.add_column("Server")
for idx, p in enumerate(profiles, 1):
table.add_row(str(idx), p.get("name", ""), p["user"],
f"{p['host']}:{p.get('port', 993)}")
console.print(table)
answer = Prompt.ask(
" Use a saved profile? Enter its number, or press Enter for a new one",
default="")
if answer.strip().isdigit() and 1 <= int(answer) <= len(profiles):
chosen = profiles[int(answer) - 1]
if chosen:
# Normalize here too — the profiles file may be edited by hand.
host, embedded_port = normalize_host(chosen["host"])
port = embedded_port or int(chosen.get("port", 993))
user = chosen["user"]
console.print(f" Using profile: [bold]{user}[/bold] @ {host}:{port}")
else:
host, embedded_port = normalize_host(
Prompt.ask(" IMAP server (e.g. imap.example.com)"))
if embedded_port:
port = embedded_port
console.print(f" Port [bold]{port}[/bold] taken from the "
"server address.")
else:
port = IntPrompt.ask(" Port", default=993)
user = Prompt.ask(" Username / e-mail address").strip()
# Hidden input needs a real terminal; when stdin is piped (scripted
# use), getpass would read from the console and hang instead.
password = Prompt.ask(
' Password [dim](any characters allowed; may be wrapped in "quotes")[/dim]',
password=sys.stdin.isatty())
password = strip_surrounding_quotes(password)
return Account(host=host, port=port, user=user, password=password)
def connect_session(account: Account, role: str):
"""Connect and authenticate; returns an ImapSession or None on failure."""
session = ImapSession(account, role=role)
session.allow_insecure_ssl = Confirm.ask(
" Use insecure SSL (skip certificate verification)?", default=True)
while True:
try:
with console.status(f"Connecting to [bold]{account.host}:{account.port}"
f"[/bold] as {account.user} ..."):
session.connect()
console.print(f" [green]OK[/green] {role}: connected and "
f"authenticated ({account.label})")
maybe_save_profile(account)
return session
except ssl.SSLCertVerificationError as exc:
console.print(f" [red]SSL certificate verification failed:[/red] {exc}")
if session.allow_insecure_ssl or not Confirm.ask(
" Connect anyway [bold red]without[/bold red] verifying "
"the certificate?", default=True):
return None
session.allow_insecure_ssl = True
except (ImapError, imaplib.IMAP4.error, OSError) as exc:
log.error("%s: connection to %s:%s as %s failed: %s",
role, account.host, account.port, account.user, exc)
console.print(f" [red]Connection to {account.host} failed:[/red] {exc}")
return None
# --------------------------------------------------------------------------
# Folder tree rendering and reports
# --------------------------------------------------------------------------
def build_tree_lines(rows):
"""rows: iterable of (parts, count, selectable).
Returns [(tree_label, count, selectable, parts), ...] with box-drawing
prefixes, suitable for both console tables and plain-text export.
"""
tree, info = {}, {}
for parts, count, selectable in rows:
node = tree
for part in parts:
node = node.setdefault(part, {})
info[tuple(parts)] = (count, selectable)
lines = []
def walk(node, prefix, path):
items = sorted(node.items(),
key=lambda kv: (kv[0].upper() != "INBOX", kv[0].lower()))
for i, (name, child) in enumerate(items):
last = i == len(items) - 1
connector = "└── " if last else "├── "
parts = path + (name,)
count, selectable = info.get(parts, (None, False))
lines.append((prefix + connector + name, count, selectable, parts))
walk(child, prefix + (" " if last else "│ "), parts)
walk(tree, "", ())
return lines
def render_tree_table(title, tree_lines, count_header="Messages"):
table = Table(title=title, box=box.ROUNDED, title_style="bold cyan",
header_style="bold")
table.add_column("Folder", overflow="fold")
table.add_column(count_header, justify="right")
total = 0
n_folders = 0
for label, count, selectable, _parts in tree_lines:
if count is None:
table.add_row(f"[dim]{rich_escape(label)}[/dim]", "[dim]—[/dim]")
else:
total += count
n_folders += 1
table.add_row(rich_escape(label), f"{count:,}")
table.add_section()
table.add_row(f"[bold]TOTAL ({n_folders} folders)[/bold]", f"[bold]{total:,}[/bold]")
return table, total, n_folders
def tree_lines_as_text(tree_lines):
width = max((len(label) for label, *_ in tree_lines), default=20) + 2
out = []
total, n_folders = 0, 0
for label, count, _selectable, _parts in tree_lines:
if count is None:
out.append(f"{label:<{width}} —")
else:
total += count
n_folders += 1
out.append(f"{label:<{width}} {count:,}")
out.append("-" * (width + 10))
out.append(f"{'TOTAL (' + str(n_folders) + ' folders)':<{width}} {total:,}")
return out
def write_report(filename: str, lines) -> Path:
"""Write a report into reports/, never overwriting an earlier one.
Report names are timestamped to the minute, so two migrations of the
same account within a minute (typical in batch runs) would otherwise
silently replace each other's report."""
path = ensure_reports_dir() / filename
stem, suffix = path.stem, path.suffix
n = 2
while path.exists():
path = path.with_name(f"{stem}_{n}{suffix}")
n += 1
with open(path, "w", encoding="utf-8") as fh:
fh.write("\n".join(lines) + "\n")
return path
def report_timestamp() -> str:
return datetime.now().strftime("%d%m%y_%H%M")
def _report_email_html(ctx, src_account, dst_account) -> str:
"""E-mail-safe HTML version of the migration report (inline styles
only, table-based layout — renders correctly in every mail client)."""
esc = html_escape
ok = ctx["ok"]
accent = "#1a7f37" if ok else "#c62828"
verdict = "VERIFIED OK" if ok else "DIFFERENCES FOUND"
info_html = "".join(
f'<tr><td style="padding:4px 14px 4px 0;color:#57606a;'
f'white-space:nowrap">{esc(k)}</td>'
f'<td style="padding:4px 0;color:#24292f">{esc(v)}</td></tr>'
for k, v in (("Source", src_account.label),
("Destination", dst_account.label),
("Copied into", ctx["copied_into"]),
("Date filter", ctx["date_filter"]),
("Date", ctx["stamp"]),
("Duration", ctx["elapsed"])))
heads = ("Folder", "Source", "Copied", "Existing", "Failed", "Missing")
head_html = "".join(
f'<th style="text-align:{"left" if h == "Folder" else "right"};'
f'padding:8px 10px;background:#24292f;color:#ffffff;'
f'font-size:12px">{h}</th>' for h in heads)
def num_cell(value, bad=False):
style = ("color:#c62828;font-weight:bold" if bad and value
else "color:#24292f")
return (f'<td style="padding:6px 10px;text-align:right;'
f'border-bottom:1px solid #eaecef;{style}">{value:,}</td>')
body_rows = []
for i, (name, srct, copied, already, failed, missing) in \
enumerate(ctx["rows"]):
body_rows.append(
f'<tr style="background:{"#ffffff" if i % 2 == 0 else "#f6f8fa"}">'
f'<td style="padding:6px 10px;border-bottom:1px solid #eaecef;'
f'color:#24292f">{esc(name)}</td>'
+ num_cell(srct) + num_cell(copied) + num_cell(already)
+ num_cell(failed, True) + num_cell(missing, True) + "</tr>")
tot = [sum(r[i] for r in ctx["rows"]) for i in range(1, 6)]
totals_html = (
'<tr><td style="padding:8px 10px;font-weight:bold;color:#24292f;'
f'border-top:2px solid #24292f">TOTAL ({len(ctx["rows"])} folders)</td>'
+ "".join(f'<td style="padding:8px 10px;text-align:right;'
f'font-weight:bold;color:#24292f;'
f'border-top:2px solid #24292f">{v:,}</td>'
for v in tot) + "</tr>")
errors_html = ""
for title, items in (