forked from rcarmo/imapbackup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimapbackup.py
More file actions
2254 lines (1904 loc) · 88.8 KB
/
imapbackup.py
File metadata and controls
2254 lines (1904 loc) · 88.8 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 -u
"""IMAP Incremental Backup Script"""
__version__ = "1.4h"
__author__ = "Rui Carmo (http://taoofmac.com)"
__copyright__ = "(C) 2006-2018 Rui Carmo. Code under MIT License.(C)"
__contributors__ = "jwagnerhki, Bob Ippolito, Michael Leonhard, Giuseppe Scrivano <gscrivano@gnu.org>, Ronan Sheth, Brandon Long, Christian Schanz, A. Bovett, Mark Feit, Marco Machicao"
# = Contributors =
# https://github.com/mmachicao: Port impapbackup core use case to python3.8. Mailbox does not support compression.
# http://github.com/markfeit: Allow password to be read from a file
# http://github.com/jwagnerhki: fix for message_id checks
# A. Bovett: Modifications for Thunderbird compatibility and disabling spinner in Windows
# Christian Schanz: added target directory parameter
# Brandon Long (Gmail team): Reminder to use BODY.PEEK instead of BODY
# Ronan Sheth: hashlib patch (this now requires Python 2.5, although reverting it back is trivial)
# Giuseppe Scrivano: Added support for folders.
# Michael Leonhard: LIST result parsing, SSL support, revamped argument processing,
# moved spinner into class, extended recv fix to Windows
# Bob Ippolito: fix for MemoryError on socket recv, http://python.org/sf/1092502
# Rui Carmo: original author, up to v1.2e
# = TODO =
# - Migrate mailbox usage from rfc822 module to email module
# - Investigate using the noseek mailbox/email option to improve speed
# - Use the email module to normalize downloaded messages
# and add missing Message-Id
# - Test parseList() and its descendents on other imapds
# - Add option to download only subscribed folders
# - Add regex option to filter folders
# - Use a single IMAP command to get Message-IDs
# - Use a single IMAP command to fetch the messages
# - Patch Python's ssl module to do proper checking of certificate chain
# - Patch Python's ssl module to raise good exceptions
# - Submit patch of socket._fileobject.read
# - Improve imaplib module with LIST parsing code, submit patch
# DONE:
# v1.4h
# - Add timeout option
# v1.3c
# - Add SSL support
# - Support host:port
# - Cleaned up code using PyLint to identify problems
# pylint -f html --indent-string=" " --max-line-length=90 imapbackup.py > report.html
import getpass
import os
import gc
import sys
import time
import getopt
import mailbox
import imaplib
import socket
import re
import hashlib
import subprocess
import tempfile
# Try to import YAML, but make it optional
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
class SkipFolderException(Exception):
"""Indicates aborting processing of current folder, continue with next folder."""
pass
class Spinner:
"""Prints out message with cute spinner, indicating progress"""
def __init__(self, message, nospinner, total=None):
"""Spinner constructor
Args:
message: Base message to display
nospinner: If True, disable spinner animation
total: Optional total count for progress tracking
"""
self.glyphs = "|/-\\"
self.pos = 0
self.message = message
self.nospinner = nospinner
self.total = total
self.current = 0
sys.stdout.write(message)
sys.stdout.flush()
self.spin()
def update(self, current=None, message=None):
"""Update progress
Args:
current: Current progress count
message: Optional message override
"""
if current is not None:
self.current = current
if message is not None:
self.message = message
self.spin()
def spin(self):
"""Rotate the spinner"""
if sys.stdin.isatty() and not self.nospinner:
display_msg = self.message
# Add progress if total is set
if self.total is not None and self.total > 0:
percentage = int((self.current / self.total) * 100)
display_msg = "%s (%d/%d, %d%%)" % (self.message, self.current, self.total, percentage)
sys.stdout.write("\r" + display_msg + " " + self.glyphs[self.pos])
sys.stdout.flush()
self.pos = (self.pos+1) % len(self.glyphs)
def stop(self):
"""Erase the spinner from the screen"""
if sys.stdin.isatty() and not self.nospinner:
display_msg = self.message
# Add final progress if total is set
if self.total is not None and self.total > 0:
display_msg = "%s (%d/%d, 100%%)" % (self.message, self.total, self.total)
sys.stdout.write("\r" + display_msg + " ")
sys.stdout.write("\r" + display_msg)
sys.stdout.flush()
def pretty_byte_count(num):
"""Converts integer into a human friendly count of bytes, eg: 12.243 MB"""
if num == 1:
return "1 byte"
elif num < 1024:
return "%s bytes" % num
elif num < 1048576:
return "%.2f KB" % (num/1024.0)
elif num < 1073741824:
return "%.3f MB" % (num/1048576.0)
elif num < 1099511627776:
return "%.3f GB" % (num/1073741824.0)
else:
return "%.3f TB" % (num/1099511627776.0)
# Regular expressions for parsing
MSGID_RE = re.compile(r"^Message-Id: (.+)", re.IGNORECASE + re.MULTILINE)
BLANKS_RE = re.compile(r'\s+', re.MULTILINE)
# Constants
UUID = '19AF1258-1AAF-44EF-9D9A-731079D6FAD7' # Used to generate Message-Ids
# Retry configuration
DEFAULT_MAX_RETRIES = 3
DEFAULT_RETRY_DELAY = 1.0 # seconds
DEFAULT_RETRY_BACKOFF = 2.0 # exponential backoff multiplier
# Memory optimization configuration
FETCH_BATCH_SIZE = 1000 # Number of messages to fetch headers for in one batch
def retry_on_network_error(func, max_retries=DEFAULT_MAX_RETRIES, delay=DEFAULT_RETRY_DELAY, backoff=DEFAULT_RETRY_BACKOFF, operation_name=None):
"""
Retry a function that may fail due to network errors.
Args:
func: Callable function to retry
max_retries: Maximum number of retry attempts
delay: Initial delay between retries in seconds
backoff: Exponential backoff multiplier
operation_name: Optional name for logging purposes
Returns:
The return value of the function if successful
Raises:
The last exception encountered if all retries fail
"""
last_exception = None
current_delay = delay
for attempt in range(max_retries):
try:
return func()
except (socket.error, socket.timeout, imaplib.IMAP4.error) as e:
last_exception = e
if attempt < max_retries - 1: # Don't sleep on last attempt
retry_msg = "Attempt %d/%d failed" % (attempt + 1, max_retries)
if operation_name:
retry_msg = "%s: %s" % (operation_name, retry_msg)
retry_msg += ". Retrying in %.1f seconds..." % current_delay
print ("\n %s" % retry_msg)
time.sleep(current_delay)
current_delay *= backoff
else:
error_msg = "All %d attempts failed" % max_retries
if operation_name:
error_msg = "%s: %s" % (operation_name, error_msg)
print ("\n %s" % error_msg)
except Exception as e:
# For non-network errors, don't retry
raise
# All retries exhausted
raise last_exception
def string_from_file(value):
"""
Read a string from a file or return the string unchanged.
If the string begins with '@', the remainder of the string
will be treated as a path to the file to be read. Precede
the '@' with a '\' to treat it as a literal.
"""
assert isinstance(value, str)
if not value or value[0] not in ["\\", "@"]:
return value
if value[0] == "\\":
return value[1:]
with open(os.path.expanduser(value[1:]), 'r') as content:
return content.read().strip()
def import_gpg_key(source):
"""
Import a GPG public key from various sources.
Supports:
- Environment variable: GPG_PUBLIC_KEY
- File path: /path/to/key.asc or ~/keys/public.asc
- URL: https://example.com/public-key.asc
- Raw key content as string
Args:
source: String containing env var name, file path, URL, or key content
Returns:
Fingerprint string if import succeeded, None otherwise
"""
try:
key_content = None
source_description = ""
# Check if GPG is available
try:
subprocess.run(['gpg', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
raise Exception("GPG not found. Please install GPG (gnupg) to use key import.")
# 1. Check environment variable
if source.startswith('env:') or source.startswith('ENV:'):
env_var = source[4:]
key_content = os.environ.get(env_var)
if not key_content:
raise Exception("Environment variable '%s' not found or empty" % env_var)
source_description = "environment variable %s" % env_var
# 2. Check if it's a URL (http:// or https://)
elif source.startswith('http://') or source.startswith('https://'):
# Retry logic for downloading GPG key
def download_key_operation():
try:
# Try curl first
try:
result = subprocess.run(
['curl', '-fsSL', source],
capture_output=True,
text=True,
check=True,
timeout=30
)
return result.stdout
except (subprocess.CalledProcessError, FileNotFoundError):
# Fall back to wget
result = subprocess.run(
['wget', '-qO-', source],
capture_output=True,
text=True,
check=True,
timeout=30
)
return result.stdout
except subprocess.TimeoutExpired:
raise socket.timeout("Timeout while downloading key")
except subprocess.CalledProcessError as e:
raise socket.error("Failed to download key: %s" % e.stderr)
try:
key_content = retry_on_network_error(
download_key_operation,
max_retries=3,
operation_name="Download GPG key from %s" % source
)
if not key_content or len(key_content) < 100:
raise Exception("Downloaded key appears to be empty or invalid")
source_description = "URL %s" % source
except Exception as e:
raise Exception("Failed to download key from URL after retries: %s" % str(e))
# 3. Check if it's a file path
elif os.path.exists(os.path.expanduser(source)):
file_path = os.path.expanduser(source)
with open(file_path, 'r') as f:
key_content = f.read()
source_description = "file %s" % file_path
# 4. Assume it's raw key content
else:
# Check if it looks like a GPG key
if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in source:
key_content = source
source_description = "provided key content"
else:
raise Exception("Invalid key source: not a valid file, URL, environment variable, or key content")
# Validate key content
if not key_content:
raise Exception("No key content found")
if '-----BEGIN PGP PUBLIC KEY BLOCK-----' not in key_content:
raise Exception("Invalid GPG key format (missing PGP PUBLIC KEY BLOCK header)")
# Import the key using GPG
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.asc') as f:
f.write(key_content)
temp_key_file = f.name
try:
# First, extract fingerprint using show-only
fingerprint = None
try:
show_cmd = ['gpg', '--batch', '--import-options', 'show-only', '--import', '--with-colons', temp_key_file]
show_result = subprocess.run(show_cmd, capture_output=True, text=True, check=True)
for line in show_result.stdout.split('\n'):
if line.startswith('fpr:'):
fields = line.split(':')
if len(fields) >= 10 and len(fields[9]) == 40:
fingerprint = fields[9]
print(" Extracted fingerprint: %s" % fingerprint)
break
except:
pass # Will try after import
# Import the key
cmd = ['gpg', '--batch', '--import', temp_key_file]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# Check if key was skipped due to missing user ID
if 'contains no user ID' in result.stderr or 'w/o user IDs' in result.stderr:
print("\nERROR: GPG key import failed - key has no user ID")
print("ERROR: The key from '%s' does not contain a user ID." % source_description)
print("ERROR: This typically happens with keys from keys.openpgp.org when the email isn't verified.")
print("ERROR:")
print("ERROR: Solutions:")
print("ERROR: 1. Verify your email on keys.openpgp.org and use the by-email URL")
print("ERROR: 2. Provide the full PGP public key block directly (with user ID)")
print("ERROR: 3. Upload your key to keyserver.ubuntu.com with full user ID")
return None
print(" Successfully imported GPG key from %s" % source_description)
# If fingerprint extraction failed before import, try after
if not fingerprint:
try:
list_cmd = ['gpg', '--batch', '--list-keys', '--with-colons']
list_result = subprocess.run(list_cmd, capture_output=True, text=True, check=True)
for line in list_result.stdout.split('\n'):
if line.startswith('fpr:'):
fields = line.split(':')
if len(fields) >= 10 and len(fields[9]) == 40:
fingerprint = fields[9]
break
except:
pass
# Return fingerprint if found, otherwise True for backwards compatibility
return fingerprint if fingerprint else True
finally:
# Clean up temp file
if os.path.exists(temp_key_file):
os.unlink(temp_key_file)
except Exception as e:
print(" WARNING: Failed to import GPG key: %s" % str(e))
return None
def encrypt_file_gpg(input_file, recipient):
"""Encrypt a file using GPG and return the path to encrypted file"""
output_file = input_file + '.gpg'
try:
# Run GPG encryption
cmd = [
'gpg',
'--batch',
'--yes',
'--trust-model', 'always',
'--no-auto-key-retrieve', # Prevent GPG from trying to fetch keys during encryption
'--encrypt',
'--recipient', recipient,
'--output', output_file,
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
if os.path.exists(output_file):
print (" Encrypted with GPG for recipient: %s" % recipient)
return output_file
else:
raise Exception("GPG encryption failed: output file not created")
except subprocess.CalledProcessError as e:
raise Exception("GPG encryption failed: %s\n%s" % (e.stderr, e.stdout))
except FileNotFoundError:
raise Exception("GPG not found. Please install GPG (gnupg) to use encryption.")
def decrypt_file_gpg(input_file):
"""Decrypt a GPG-encrypted file and return the path to decrypted file"""
# Remove .gpg extension for output file
if input_file.endswith('.gpg'):
output_file = input_file[:-4]
else:
output_file = input_file + '.decrypted'
try:
# Run GPG decryption
cmd = [
'gpg',
'--batch',
'--yes',
'--decrypt',
'--output', output_file,
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
if os.path.exists(output_file):
print (" Decrypted: %s" % os.path.basename(input_file))
return output_file
else:
raise Exception("GPG decryption failed: output file not created")
except subprocess.CalledProcessError as e:
raise Exception("GPG decryption failed: %s\n%s" % (e.stderr, e.stdout))
except FileNotFoundError:
raise Exception("GPG not found. Please install GPG (gnupg) to use decryption.")
def download_from_s3(filename, config, destination_dir):
"""Download a file from S3-compatible storage using AWS CLI with retry logic"""
# Check if aws CLI is available
try:
subprocess.run(['aws', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
raise Exception("AWS CLI not found. Please install awscli to use S3 download.")
# Prepare S3 object key
s3_prefix = config.get('s3_prefix', '').rstrip('/')
if s3_prefix:
s3_key = s3_prefix + '/' + filename
else:
s3_key = filename
s3_uri = 's3://%s/%s' % (config['s3_bucket'], s3_key)
# Destination path
destination_path = os.path.join(destination_dir, filename)
# Set up environment variables for AWS credentials
env = os.environ.copy()
env['AWS_ACCESS_KEY_ID'] = config['s3_access_key']
env['AWS_SECRET_ACCESS_KEY'] = config['s3_secret_key']
# Build AWS CLI command
cmd = [
'aws', 's3', 'cp',
s3_uri,
destination_path,
'--endpoint-url', config['s3_endpoint']
]
print (" Downloading from S3: %s" % s3_uri)
# Retry logic for S3 download
def download_operation():
try:
result = subprocess.run(cmd, env=env, capture_output=True, text=True, check=True, timeout=300)
return result
except subprocess.CalledProcessError as e:
# Treat S3 download failures as network errors that should be retried
raise socket.error("S3 download failed: %s" % e.stderr)
except subprocess.TimeoutExpired:
raise socket.timeout("S3 download timed out")
try:
retry_on_network_error(
download_operation,
max_retries=3,
operation_name="S3 download %s" % filename
)
print (" Download complete")
return destination_path
except Exception as e:
raise Exception("S3 download failed after retries: %s" % str(e))
def upload_to_s3(file_path, config):
"""Upload a file to S3-compatible storage using AWS CLI with retry logic"""
# Check if aws CLI is available
try:
subprocess.run(['aws', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
raise Exception("AWS CLI not found. Please install awscli to use S3 upload.")
# Prepare S3 object key
filename = os.path.basename(file_path)
s3_prefix = config.get('s3_prefix', '').rstrip('/')
if s3_prefix:
s3_key = s3_prefix + '/' + filename
else:
s3_key = filename
s3_uri = 's3://%s/%s' % (config['s3_bucket'], s3_key)
# Set up environment variables for AWS credentials
env = os.environ.copy()
env['AWS_ACCESS_KEY_ID'] = config['s3_access_key']
env['AWS_SECRET_ACCESS_KEY'] = config['s3_secret_key']
# Build AWS CLI command
cmd = [
'aws', 's3', 'cp',
file_path,
s3_uri,
'--endpoint-url', config['s3_endpoint']
]
print (" Uploading to S3: %s" % s3_uri)
# Retry logic for S3 upload
def upload_operation():
try:
result = subprocess.run(cmd, env=env, capture_output=True, text=True, check=True, timeout=300)
return result
except subprocess.CalledProcessError as e:
# Treat S3 upload failures as network errors that should be retried
raise socket.error("S3 upload failed: %s" % e.stderr)
except subprocess.TimeoutExpired:
raise socket.timeout("S3 upload timed out")
try:
retry_on_network_error(
upload_operation,
max_retries=3,
operation_name="S3 upload %s" % filename
)
print (" Upload complete")
return True
except Exception as e:
raise Exception("S3 upload failed after retries: %s" % str(e))
def upload_messages(server, foldername, filename, messages_to_upload, nospinner, basedir):
"""Upload messages from mbox file to IMAP folder
Returns:
tuple: (uploaded_count, failed_count, total_bytes)
"""
fullname = os.path.join(basedir, filename)
uploaded = 0
failed = 0
total_size = 0
# Check if file exists
if not os.path.exists(fullname):
print ("File %s: not found, skipping" % filename)
return (0, len(messages_to_upload), 0)
# nothing to do
if not len(messages_to_upload):
print ("Messages to upload: 0")
return (0, 0, 0)
total_messages = len(messages_to_upload)
spinner = Spinner("Uploading messages to %s" % foldername,
nospinner, total=total_messages)
try:
# Open the mbox file
try:
mbox = mailbox.mbox(fullname)
except (IOError, OSError) as e:
spinner.stop()
print ("\nERROR: Cannot open mbox file %s: %s" % (fullname, str(e)))
return (0, len(messages_to_upload), 0)
except Exception as e:
spinner.stop()
print ("\nERROR: Mailbox file %s is corrupted or invalid: %s" % (fullname, str(e)))
return (0, len(messages_to_upload), 0)
# Iterate through messages in the mbox file
msg_index = 0
try:
for message in mbox:
try:
# Get the Message-Id
try:
msg_id = message.get('Message-Id', '').strip()
except Exception as e:
print ("\nWARNING: Cannot read Message-Id from message: %s" % str(e))
failed += 1
continue
# Check if this message needs to be uploaded
if msg_id in messages_to_upload:
msg_index += 1
spinner.update(current=msg_index)
# Convert message to string (bytes)
try:
msg_bytes = bytes(str(message), 'utf-8')
except Exception as e:
print ("\nERROR: Cannot convert message %s to bytes: %s" % (msg_id, str(e)))
failed += 1
continue
# Upload to IMAP server with retry logic
# Use APPEND command to add message to folder
try:
foldername_quoted = '"{}"'.format(foldername)
# APPEND the message with retry
def append_operation():
return server.append(foldername_quoted, None, None, msg_bytes)
result = retry_on_network_error(
append_operation,
operation_name="Upload message %s" % msg_id
)
if result[0] == 'OK':
uploaded += 1
total_size += len(msg_bytes)
else:
print ("\nWARNING: Failed to upload message with ID %s: %s" % (msg_id, result))
failed += 1
except (imaplib.IMAP4.error, socket.error, socket.timeout) as e:
print ("\nERROR: Network error uploading message %s after retries: %s" % (msg_id, str(e)))
failed += 1
except Exception as e:
print ("\nERROR: Unexpected error uploading message %s: %s" % (msg_id, str(e)))
failed += 1
except Exception as e:
print ("\nERROR: Error processing message for upload: %s" % str(e))
failed += 1
except Exception as e:
spinner.stop()
print ("\nERROR: Error reading messages from mbox: %s" % str(e))
try:
mbox.close()
except:
pass
return (uploaded, len(messages_to_upload) - uploaded, total_size)
try:
mbox.close()
except Exception as e:
print ("\nWARNING: Error closing mbox file %s: %s" % (filename, str(e)))
spinner.stop()
if failed > 0:
print (": %s uploaded, %s total (%d failed)" % (uploaded, pretty_byte_count(total_size), failed))
else:
print (": %s uploaded, %s total" % (uploaded, pretty_byte_count(total_size)))
return (uploaded, failed, total_size)
except Exception as e:
spinner.stop()
print ("\nERROR: Fatal error in upload_messages: %s" % str(e))
return (uploaded, len(messages_to_upload) - uploaded, total_size)
def download_messages(server, filename, messages, overwrite, nospinner, thunderbird, basedir, icloud):
"""Download messages from folder and append to mailbox
Returns:
tuple: (success_count, failed_count, total_bytes)
"""
fullname = os.path.join(basedir,filename)
success_count = 0
failed_count = 0
total = 0
biggest = 0
try:
if overwrite and os.path.exists(fullname):
print ("Deleting mbox: {0} at: {1}".format(filename,fullname))
try:
os.remove(fullname)
except OSError as e:
print ("ERROR: Cannot delete file %s: %s" % (fullname, str(e)))
return (0, len(messages), 0)
# Open disk file for append in binary mode
try:
mbox = open(fullname, 'ab')
except IOError as e:
print ("ERROR: Cannot open file %s for writing: %s" % (fullname, str(e)))
return (0, len(messages), 0)
# nothing to do
if not len(messages):
print ("New messages: 0")
mbox.close()
return (0, 0, 0)
total_messages = len(messages)
spinner = Spinner("Downloading messages to %s" % filename,
nospinner, total=total_messages)
from_re = re.compile(b"\n(>*)From ")
# each new message
msg_index = 0
for msg_id in messages.keys():
msg_index += 1
spinner.update(current=msg_index)
try:
# This "From" and the terminating newline below delimit messages
# in mbox files. Note that RFC 4155 specifies that the date be
# in the same format as the output of ctime(3), which is required
# by ISO C to use English day and month abbreviations.
buf = "From nobody %s\n" % time.ctime()
# If this is one of our synthesised Message-IDs, insert it before
# the other headers
if UUID in msg_id:
buf = buf + "Message-Id: %s\n" % msg_id
# convert to bytes before writing to file of type binary
buf_bytes=bytes(buf,'utf-8')
mbox.write(buf_bytes)
# fetch message with retry logic
msg_id_str = str(messages[msg_id])
try:
def fetch_operation():
return server.fetch(msg_id_str, "(BODY.PEEK[])" if icloud else "(RFC822)")
typ, data = retry_on_network_error(
fetch_operation,
operation_name="Fetch message %s" % msg_id_str
)
except (imaplib.IMAP4.error, socket.error, socket.timeout) as e:
print ("\nWARNING: Failed to fetch message %s after retries: %s" % (msg_id_str, str(e)))
failed_count += 1
continue
if typ != 'OK' or not data or not data[0]:
print ("\nWARNING: FETCH returned unexpected response for message %s" % msg_id_str)
failed_count += 1
continue
try:
data_bytes = data[0][1]
except (IndexError, TypeError) as e:
print ("\nWARNING: Cannot extract data from message %s: %s" % (msg_id_str, str(e)))
failed_count += 1
continue
text_bytes = data_bytes.strip().replace(b'\r', b'')
if thunderbird:
# This avoids Thunderbird mistaking a line starting "From " as the start
# of a new message. _Might_ also apply to other mail lients - unknown
text_bytes = text_bytes.replace(b"\nFrom ", b"\n From ")
else:
# Perform >From quoting as described by RFC 4155 and the qmail docs.
# https://www.rfc-editor.org/rfc/rfc4155.txt
# http://qmail.org/qmail-manual-html/man5/mbox.html
text_bytes = from_re.sub(b"\n>\\1From ", text_bytes)
try:
mbox.write(text_bytes)
mbox.write(b'\n\n')
except IOError as e:
print ("\nERROR: Failed to write message %s to disk: %s" % (msg_id_str, str(e)))
failed_count += 1
continue
size = len(text_bytes)
biggest = max(size, biggest)
total += size
success_count += 1
del data
gc.collect()
except Exception as e:
# Catch-all for unexpected errors
print ("\nERROR: Unexpected error processing message %s: %s" % (msg_id, str(e)))
failed_count += 1
mbox.close()
spinner.stop()
if failed_count > 0:
print (": %s total, %s for largest message (%d succeeded, %d failed)" %
(pretty_byte_count(total), pretty_byte_count(biggest), success_count, failed_count))
else:
print (": %s total, %s for largest message" % (pretty_byte_count(total),
pretty_byte_count(biggest)))
return (success_count, failed_count, total)
except Exception as e:
print ("ERROR: Fatal error in download_messages for %s: %s" % (filename, str(e)))
return (success_count, len(messages) - success_count, total)
def scan_file(filename, overwrite, nospinner, basedir):
"""Gets IDs of messages in the specified mbox file
Returns:
dict: Dictionary of message IDs found in file, or empty dict on error
"""
# file will be overwritten
if overwrite:
return {}
fullname = os.path.join(basedir,filename)
# file doesn't exist
if not os.path.exists(fullname):
print ("File %s: not found" % filename)
return {}
spinner = Spinner("File %s" % filename, nospinner)
messages = {}
try:
# open the mailbox file for read
try:
mbox = mailbox.mbox(fullname)
except (IOError, OSError) as e:
spinner.stop()
print ("\nERROR: Cannot open mbox file %s: %s" % (fullname, str(e)))
return {}
except Exception as e:
spinner.stop()
print ("\nERROR: Mailbox file %s is corrupted or invalid: %s" % (fullname, str(e)))
return {}
# each message
i = 0
HEADER_MESSAGE_ID='Message-Id'
try:
for message in mbox:
try:
header = ''
# We assume all messages on disk have message-ids
try:
header = "{0}: {1}".format(HEADER_MESSAGE_ID,message.get(HEADER_MESSAGE_ID))
except KeyError:
# No message ID was found. Warn the user and move on
print ("\nWARNING: Message #%d in %s has no {0} header.".format(HEADER_MESSAGE_ID) % (i, filename))
i += 1
spinner.spin()
continue
except Exception as e:
print ("\nWARNING: Cannot read headers from message #%d in %s: %s" % (i, filename, str(e)))
i += 1
spinner.spin()
continue
header = BLANKS_RE.sub(' ', header.strip())
try:
msg_id = MSGID_RE.match(header).group(1)
if msg_id not in messages.keys():
# avoid adding dupes
messages[msg_id] = msg_id
except (AttributeError, IndexError):
# Message-Id was found but could somehow not be parsed by regexp
print ("\nWARNING: Message #%d in %s has a malformed {0} header.".format(HEADER_MESSAGE_ID) % (i, filename))
except Exception as e:
# Catch-all for unexpected errors processing individual message
print ("\nWARNING: Error processing message #%d in %s: %s" % (i, filename, str(e)))
spinner.spin()
i = i + 1
except Exception as e:
# Error iterating through mailbox
spinner.stop()
print ("\nERROR: Failed while reading mailbox %s: %s" % (filename, str(e)))
print ("Recovered %d messages before error" % len(messages))
try:
mbox.close()
except:
pass
return messages
# done
try:
mbox.close()
except Exception as e:
print ("\nWARNING: Error closing mbox file %s: %s" % (filename, str(e)))
spinner.stop()
print (": %d messages" % (len(messages.keys())))
return messages
except Exception as e:
spinner.stop()
print ("\nERROR: Fatal error in scan_file for %s: %s" % (filename, str(e)))
return {}
def scan_folder(server, foldername, nospinner):
"""Gets IDs of messages in the specified folder, returns id:num dict
Returns:
dict: Dictionary mapping message IDs to message numbers, or empty dict on error
Raises:
SkipFolderException: When folder cannot be accessed (to allow continuing with next folder)
"""
messages = {}
foldername_quoted = '"{}"'.format(foldername)
spinner = None # Will be initialized after we know num_msgs
try:
# Select the folder with retry logic
try:
def select_operation():
return server.select(foldername_quoted, readonly=True)
typ, data = retry_on_network_error(
select_operation,
operation_name="Select folder %s" % foldername_quoted
)
except (imaplib.IMAP4.error, socket.error, socket.timeout) as e:
raise SkipFolderException("SELECT failed for %s after retries: %s" % (foldername_quoted, str(e)))
except Exception as e:
raise SkipFolderException("Unexpected error selecting folder %s: %s" % (foldername_quoted, str(e)))
if 'OK' != typ:
raise SkipFolderException("SELECT failed: %s" % data)
try:
num_msgs = int(data[0])
except (ValueError, IndexError, TypeError) as e:
raise SkipFolderException("Cannot parse message count for %s: %s" % (foldername_quoted, str(e)))
# Initialize spinner with total message count for progress tracking
spinner = Spinner("Folder %s" % foldername_quoted, nospinner, total=num_msgs)
# Retrieve Message-Id headers in batches to avoid memory issues with large mailboxes
# Process messages in batches of FETCH_BATCH_SIZE to keep memory usage constant
if num_msgs > 0:
# Process messages in batches
for batch_start in range(1, num_msgs + 1, FETCH_BATCH_SIZE):
batch_end = min(batch_start + FETCH_BATCH_SIZE - 1, num_msgs)
batch_range = '%d:%d' % (batch_start, batch_end)
# Fetch headers for this batch
# The result is an array of result tuples with a terminating closing parenthesis
# after each tuple. That means that the first result is at index 0, the second at
# 2, third at 4, and so on.
try:
def fetch_headers_operation():
return server.fetch(batch_range, '(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)])')
typ, data = retry_on_network_error(
fetch_headers_operation,
operation_name="Fetch headers %s from %s" % (batch_range, foldername_quoted)
)
except (imaplib.IMAP4.error, socket.error, socket.timeout) as e:
spinner.stop()
raise SkipFolderException("FETCH failed for %s after retries: %s" % (foldername_quoted, str(e)))
except Exception as e:
spinner.stop()
raise SkipFolderException("Unexpected error fetching headers from %s: %s" % (foldername_quoted, str(e)))