-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathemail2file.py.asc
More file actions
2473 lines (2040 loc) · 104 KB
/
email2file.py.asc
File metadata and controls
2473 lines (2040 loc) · 104 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
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
#!/usr/bin/env python
#
##### EMAIL2FILE v2.42!
##### AUTHOR: vvn < root @ nobody . ninja >
##### VERSION RELEASE: March 16, 2017
##### GPG public key: F6679EC4
#
##### SAVE EMAIL LISTS AS PLAIN TEXT format in script directory with one address per line.
##### you can include the password, if known, as a base64-encoded string
##### separated by a comma. just use "email@addy.com, encoded_password"
##### on each line instead.
#####
##### PASSWORD LISTS SHOULD BE ONE PASSWORD PER LINE.
##### they can also be base64-encoded or encrypted. you can either run
##### "python encodelist.py" to base64-encode or "python encryptlist.py" to
##### encrypt the list, or select the option to encode or encrypt the list
##### while running this script (email2file.py).
#####
##### ENCRYPTION NOW FULLY WORKING FOR PASSWORD LISTS!
##### the feature has now been fully integrated into the main script!
##### use the encryption feature to securely store your password lists,
##### and decrypt them for use with the script. it is highly recommended
##### that you delete the plaintext files after script completes.
#####
##### YOUR ENCRYPTION KEY is stored as 'secret.key' by default, in the
##### current working directory. YOUR SECRET PASSPHRASE CANNOT BE RECOVERED
##### IF FORGOTTEN. the program cannot verify if an incorrect passphrase
##### is entered during the decryption process, and the result will be
##### invalid data that is returned. do not forget your secret passphrase,
##### or write it down and store it in a secure location.
#
##### DECRYPTING GPG EMAILS WORKS NOW! YAY!
#
##### ALSO *FINALLY* GOT MULTIPLE FILE ATTACHMENTS WORKING! they even
##### get saved in the proper encoding!
#####
##### TO RUN SCRIPT: open terminal to script directory and enter:
##### "python email2file.py"
#
##### **PLEASE USE PYTHON 2.7.X AND NOT PYTHON 3**
##### OR YOU WILL GET SYNTAX ERRORS!
#####
##### works best on OSX and linux systems, but you can try it on windows.
##### i even went to the trouble of trying to remove ANSI color codes for you
##### windows users, so you'd better use it! if you are on windows, you can
##### install the colorama or ansiterm python module to support ANSI colors.
##### if you have setuptools or pip installed, you can easily get it by
##### opening a MS-DOS window as administrator and typing the following:
##### "pip install colorama" or "pip install ansiterm"
##### you can get pip by entering: "easy_install pip"
#####
##### depending on the text encoding of the original email, each message
##### is saved as a TXT or HTM file. the files can be found in the
##### respective account subfolder within the 'emails' directory in
##### the current working directory, or a user-specified location.
##### for example, a message from sender@email.com with subject "test"
##### in rich text format received at user@email.com will output to:
##### <cwd>/emails/user_email.com/01-"sender" <sender@email.com> .htm
##### where <cwd> is the current working directory. this can be changed
##### when running the program at the beginning.
#####
##### a file of all mail headers is also saved in the 'emails' directory.
##### it should be called user@email.com-headerlist-yyyy-mm-dd.txt
#####
##### attachments are saved either in account folder or 'attachments' subfolder.
#####
##### logs will be saved in the 'logs' folder inside the 'emails' directory
##### or the user-specified location.
#####
##### ****KNOWN BUGS (3/16/2017):****
##### - socket.error "[Errno 54] Connection reset by peer"
##### will interrupt the script execution. in case that it happens,
##### just start the script again:
##### python email2file.py or chmod +x *.py && ./email2file.py
##### - GPG signature verification always seems to fail, usually with
##### 969 bytes-sized files named "signature.asc"
##### - yes there's a lot of redundant code and message content might
##### get saved more than once because i wasn't sure what worked!
#####
##### if you run tor and proxychains, you can run the script within proxychains:
##### proxychains python email2file.py
#####
##### * latest release should always be found on github:
##### http://github.com/eudemonics/email2file
##### * download using terminal command:
##### git clone https://github.com/eudemonics/email2file.git email2file
##################################################
##################################################
##### USER LICENSE AGREEMENT & DISCLAIMER
##### copyright, copyleft (C) 2014-2017 vvn < root @ nobody . ninja >
#####
##### This program is FREE software: you can use it, redistribute it and/or modify
##### it as you wish. Copying and distribution of this file, with or without modification,
##### are permitted in any medium without royalty provided the copyright
##### notice and this notice are preserved. This program is offered AS-IS,
##### WITHOUT ANY WARRANTY; without even the implied warranty of
##### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##### GNU General Public License for more details.
##################################################
##################################################
##### getting credited for my work is nice. so are donations.
##### BTC: 1M511j1CHR8x7RYgakNdw1iF3ike2KehXh
##### https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=26PWMPCNKN28L
##### but to really show your appreciation, you should buy my EP instead!
##### you can stream and purchase it at: http://dreamcorp.us
##### (you might even enjoy listening to it)
##### and follow on facebook: https://facebook.com/dreamcorporation
##### i also run a news site, SNOOZE PRESS! visit here: http://snooze.press
#####
##### questions, comments, feedback, bugs, complaints, death threats, marriage proposals?
##### contact me at: root @ nobody [dot] ninja
##### there be only about two thousand lines of code after this -->
from __future__ import print_function
import email, base64, getpass, imaplib, threading
from email.header import decode_header
from email.parser import Parser
import re, sys, os, os.path, socket, time, traceback, logging
from subprocess import Popen
from datetime import datetime, date
from threading import Thread, Timer
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util import Counter
from ansilist import ac
try:
import gnupg
except:
pass
try:
os.system('pip install python-gnupg')
import gnupg
except:
pass
print('\nunable to install gnupg module. you may need to run the \'easy_install python-gnupg\' command with administrator privileges. GPG decryption and signature validation will be disabled.\n')
use_gpg = 0
colorintro = '''
\033[34m=====================================\033[33m
- ---------\033[36m EMAIL2FILE v2.42 \033[33m----------
- -------------------------------------
- -----------\033[35m author : vvn \033[33m------------
- ---------\033[32m root@nobody.ninja \033[33m---------
\033[34m=====================================\033[33m
- ----\033[37m support my work: buy my EP! \033[33m----
- --------\033[37m http://dreamcorp.us \033[33m--------
- ---\033[37m facebook.com/dreamcorporation \033[33m---
- ------\033[32m thanks for the support! \033[33m------
\033[34m=====================================\n\033[0m
'''
cleanintro = '''
=====================================
- --------- EMAIL2FILE v2.42 ----------
- -------------------------------------
- ----------- author : vvn ------------
- --------- root@nobody.ninja ---------
=====================================
- ---- support my work: buy my EP! ----
- -------- http://dreamcorp.us --------
- --- facebook.com/dreamcorporation ---
- ------ thanks for the support! ------
=====================================
'''
global usecolor
global emailaddr
global imap_server
global completed
if os.name == 'nt' or sys.platform == 'win32':
try:
import colorama
colorama.init()
usecolor = "color"
progintro = colorintro
except:
pass
try:
os.system('pip install colorama')
import colorama
colorama.init()
usecolor = "color"
progintro = colorintro
except:
pass
try:
import tendo.ansiterm
usecolor = "color"
progintro = colorintro
except:
usecolor = "clean"
progintro = cleanintro
pass
else:
usecolor = "color"
progintro = colorintro
scriptpath = os.path.realpath(sys.argv[0])
scriptdir = os.path.dirname(scriptpath)
sys.path.insert(0, scriptdir)
#print('***DEBUG*** \nscript path: %s \nscript dir: %s \n' % (scriptpath, scriptdir))
print(progintro)
time.sleep(0.9)
############################
# START PROGRAM #
############################
# CHECK IF SINGLE EMAIL (1) OR LIST OF MULTIPLE EMAIL ADDRESSES IS USED (2)
print('''
\033[34;1mSINGLE EMAIL ADDRESS OR LIST OF MULTIPLE EMAIL ADDRESSES?\033[0m
list of multiple email addresses must be in text format
with one email address per line. PASSWORD LIST with one
password per line in plain text or base64 encoded format
supported. ENCRYPTION MODULE also now fully supported! To
encrypt password list, run \033[36;1mpython encryptlist.py\033[0m.
***ALSO SUPPORTS EMAIL AND PASSWORD IN A SINGLE FILE:***
one email address + one password (plaintext or base64 encoded)
per line separated by a comma (example@domain.com, password)
''')
qtyemail = raw_input('enter 1 for single email or 2 for multiple emails --> ')
print('')
while not re.search(r'^[12]$', qtyemail):
qtyemail = raw_input('invalid entry. enter 1 for a single email address, or enter 2 to specify a list of multiple email addresses in text format --> ')
# CHECK IF WORD LIST USED FOR PASSWORD
usewordlist = raw_input('do you want to use a word list rather than supply a password? enter Y/N --> ')
while not re.search(r'^[nyNY]$', usewordlist):
usewordlist = raw_input('invalid entry. enter Y to use word list or N to supply password --> ')
print('')
# SET DOWNLOAD DIRECTORY
changedir = raw_input('inbox contents will be saved to \'emails\' folder by default. would you like to change this? Y/N --> ')
while not re.search(r'^[nyNY]$', changedir):
changedir = raw_input('invalid entry. enter Y to change save directory or N to use default --> ')
print('')
homedir = os.path.expanduser("~")
gpgdir = os.path.join(homedir, '.gnupg')
cwd = os.getcwd()
outputdir = 'emails'
savedir = os.path.join(cwd, outputdir)
completed = []
if changedir.lower() == 'y':
savedir = raw_input('please enter the full path of where to save inbox contents --> ')
if os.name == 'nt' or sys.platform == 'win32':
matchstr = r'^[a-zA-Z]:\\(((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$'
else:
matchstr = r'^[^\0]+$'
while not re.match(matchstr, savedir):
savedir = raw_input('invalid path. please enter a valid output directory --> ')
print('')
if not os.path.exists(savedir):
os.makedirs(savedir, 0755)
ustimefmt = lambda a: date.strftime(a,"%m/%d/%Y %I:%M%p")
today = datetime.now()
today = date.strftime(today,"%m-%d-%Y")
logdir = os.path.join(savedir, 'logs')
if not os.path.exists(logdir):
os.makedirs(logdir, 0755)
logfile = 'email2file-' + today + '.log'
logfile = os.path.join(logdir, logfile)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%a, %d %b %Y %I:%M%p',
filename=logfile,
filemode='ab+')
# CHECK IF SSL USED TO CONNECT TO IMAP SERVER
usesslcheck = raw_input('use SSL? Y/N --> ')
while not re.search(r'^[nyNY]$', usesslcheck):
usesslcheck = raw_input('invalid selection. please enter Y for SSL or N for unencrypted connection. -->')
print('')
sslcon = 'yes'
if usesslcheck.lower() == 'n':
sslcon = 'no'
else:
sslcon = 'yes'
print('''
prompt with option to reveal correct password in
terminal on successful login?
\033[1m**entering Y will pause the program
to wait for user input!!** \033[0m
**enter N to let the script run without interruptions**
''')
showpasscheck = raw_input('please enter Y/N --> ')
while not re.search(r'^[nyNY]$', showpasscheck):
showpasscheck = raw_input('invalid entry. please enter Y to ask if you want the correct password revealed upon successful login, or N to let the script run uninterrupted --> ')
passprompt = 0
if showpasscheck.lower() == 'y':
passprompt = 1
else:
passprompt = 0
print('')
# FUNCTION TO RESOLVE IMAP SERVER
def resolveimap(imap_server):
server_ip = imap_server
resolved_ips = []
try:
nscheck = socket.getaddrinfo(imap_server,0,0,0,0)
for result in nscheck:
resolved_ips = list(set(result))
except socket.error as e:
pass
logging.warning('unable to resolve %s' % imap_server)
logging.warning('caught exception: %s' % str(e))
if usecolor == 'color':
print(ac.YELLOW + 'ERROR: ' + ac.OKAQUA + 'could not resolve ' + ac.OKPINK + imap_server + ac.CLEAR)
else:
print('ERROR: could not resolve %s' % imap_server)
print('\nerror: %s \n' % str(e))
imap_server = raw_input('please enter a valid IMAP server --> ')
while not re.search(r'^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$', imap_server):
imap_server = raw_input('invalid hostname. please enter a valid IMAP server --> ')
print('')
nscheck = socket.getaddrinfo(imap_server,0)
for result in nscheck:
resolved_ips = list(set(result))
#print(resolved_ips)
finally:
if len(resolved_ips) > 1:
if len(str(resolved_ips[3])) > 1:
server_ip = resolved_ips[3][0]
else:
server_ip = resolved_ips[4][0]
if usecolor == 'color':
showip = ac.GREENBOLD + str(server_ip) + ac.CLEAR
else:
showip = str(server_ip)
print('\nRESOLVED SERVER TO: %s \n' % showip)
logging.info('resolved %s to: %s' % (imap_server, server_ip))
else:
print('\nERROR: no response from DNS server; could not resolve %s.\n' % imap_server)
logging.warning('no response from DNS server. unable to resolve %s.' % imap_server)
return imap_server, server_ip
# FUNCTION TO CHECK LOGIN CREDENTIALS
def checklogin(emailaddr, emailpass, imap_server, sslcon):
global checkresp
loginstatus = 'BAD'
efmatch = re.search(r'^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$', emailaddr)
while not efmatch:
emailaddr = raw_input('invalid email format. enter a valid email address --> ')
print('')
imap_port = 993
if 'no' in sslcon:
imap_port = 143
if 'gmail.com' in emaildomain:
imap_port = 587
if 'yes' in sslcon:
server = imaplib.IMAP4_SSL(imap_server, imap_port)
else:
server = imaplib.IMAP4(imap_server, imap_port)
checkresp = 'preconnect'
if usecolor == 'color':
print('\nattempting to log onto: ' + ac.GREEN + emailaddr + ac.CLEAR)
else:
print('\nattempting to log onto: %s' % emailaddr)
logging.info('attempting to connect to IMAP server to check login credentials for account %s' % emailaddr)
try:
loginstatus, logindata = server.login(emailaddr, emailpass)
loginstatus = str(loginstatus)
if 'OK' in loginstatus:
if usecolor == 'color':
print(ac.WHITEBOLD + '\nLOGIN SUCCESSFUL: ' + ac.PINKBOLD + emailaddr + ac.CLEAR + '\n')
else:
print('\nLOGIN SUCCESSFUL: %s\n' % emailaddr)
logging.info('INFO: LOGIN successful for account %s' % emailaddr)
checkresp = 'OK'
elif 'AUTHENTICATIONFAILED' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s with %s \n' % (loginstatus, logindata)
print(loginmsg)
logging.warning('ERROR: %s for account %s') % (loginmsg, emailaddr)
checkresp = 'AUTHENFAIL'
elif 'PRIVACYREQUIRED' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s with %s \n' % (loginstatus, logindata)
print(loginmsg)
logging.warning('ERROR: %s for account %s') % (loginmsg, emailaddr)
checkresp = 'PRIVACYREQ'
elif 'UNAVAILABLE' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s with %s \n' % (loginstatus, logindata)
print(loginmsg)
logging.warning('ERROR: %s for account %s') % (loginmsg, emailaddr)
checkresp = 'UNAVAIL'
elif 'AUTHORIZATIONFAILED' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s with %s \n' % (loginstatus, logindata)
print(loginmsg)
logging.warning('ERROR: %s for account %s') % (loginmsg, emailaddr)
checkresp = 'AUTHORFAIL'
elif 'EXPIRED' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s with %s \n' % (loginstatus, logindata)
print(loginmsg)
logging.warning('ERROR: %s for account %s') % (loginmsg, emailaddr)
checkresp = 'EXPIRED'
elif 'CONTACTADMIN' in loginstatus:
loginmsg = '\nLOGIN FAILED: %s \n' % loginstatus
print(loginmsg)
logging.warning('%s for account %s') % (loginmsg, emailaddr)
checkresp = 'ADMINREQ'
else:
print('\nUnable to connect: %s \n' % emailaddr)
logging.error('%s for account %s') % (loginstatus, emailaddr)
checkresp = 'UNKNOWN'
except IOError as e:
pass
if usecolor == 'color':
print('\nconnection attempt to ' + ac.PINKBOLD + emailaddr + ac.CLEAR + ' failed with IO error: \n' + ac.AQUA + str(e) + ' \n' + ac.CLEAR)
else:
print('\nconnection attempt to %s failed with IO error: \n%s \n' % (emailaddr, str(e)))
logging.error('IO ERROR: %s for account %s') % (str(e), emailaddr)
checkresp = 'IOERROR'
except socket.error as e:
pass
if usecolor == 'color':
print('\nconnection attempt to ' + ac.PINKBOLD + emailaddr + ac.CLEAR + ' failed with socket error: \n' + ac.AQUA + str(e) + ' \n' + ac.CLEAR)
else:
print('\nconnection attempt to %s failed with socket error: \n%s \n' % (emailaddr, str(e)))
logging.error('SOCKET ERROR: %s for account %s') % (str(e), emailaddr)
checkresp = 'SOCKETERROR'
except server.error as e:
pass
if usecolor == 'color':
print('\nconnection attempt to ' + ac.PINKBOLD + emailaddr + ac.CLEAR + ' failed with IMAP error: \n' + ac.AQUA + str(e) + ' \n' + ac.CLEAR)
else:
print('\nconnection attempt to %s failed with IMAP error: \n%s \n' % (emailaddr, str(e)))
logging.error('IMAPLIB ERROR: ' + str(e) + ' for account ' + emailaddr)
checkresp = 'IMAPERROR'
if 'BAD' in str(e):
if usecolor == 'color':
print('\nerror connecting to ' + ac.PINKBOLD + emailaddr + ac.CLEAR + ': \n' + ac.AQUA + str(e) + ' \n' + ac.CLEAR)
else:
print('\nerror connecting to %s: \n%s \n' % (emailaddr, str(e)))
checkresp = 'BAD'
logging.error('BAD RESPONSE: connection to %s failed with error - %s \n' % (emailaddr, str(e)))
else:
checkresp = checkresp + 'ERROR'
except socket.timeout as e:
pass
print('SOCKET TIMEOUT: %s' % str(e))
logging.error(str(e) + ' - Socket timeout while logging onto account ' + str(emailaddr))
checkresp = 'TIMEOUT'
except:
pass
if 'OK' in loginstatus:
if usecolor == 'color':
print(ac.WHITEBOLD + '\nLOGIN SUCCESSFUL: ' + ac.PINKBOLD + emailaddr + ac.CLEAR + '\n')
else:
print('\nLOGIN SUCCESSFUL: %s \n' % emailaddr)
logging.info('LOGIN successful for account %s' % emailaddr)
checkresp = 'OK'
else:
checkimap = raw_input('error logging onto ' + imap_server + '. to use a different IMAP server, enter it here. else, press ENTER to continue --> ')
logging.warning('UNKNOWN ERROR occurred while trying to log onto account %s' % emailaddr)
if len(checkimap) > 0:
while not re.search(r'^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$', checkimap):
checkimap = raw_input('invalid format. please enter a valid IMAP server --> ')
imap_server = checkimap
if 'yes' in sslcon:
server = imaplib.IMAP4_SSL(imap_server, imap_port)
else:
server = imaplib.IMAP4(imap_server, imap_port)
try:
loginstatus, logindata = server.login(emailaddr, emailpass)
if 'OK' in loginstatus:
checkresp = 'OK'
else:
checkresp = loginstatus[:8]
except e:
pass
logging.error('exception occurred while attempting logon for %s: %s' % (emailaddr, str(e)))
checkresp = 'OTHERERROR'
return checkresp
# END OF FUNCTION checklogin()
# FUNCTION TO CHECK FOR EMAIL FORMAT ERRORS BEFORE SUBMITTING TO SERVER
def checkformat(emailaddr):
emailformat = "unchecked"
match = re.search(r'^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,16})$', emailaddr)
if not match:
emailformat = "bad"
logging.warning('bad email address format for entry: %s' % str(emailaddr))
if usecolor == 'color':
print('\033[31minvalid email format \033[0m\n')
else:
print('invalid email format')
else:
emailformat = "good"
logging.info('email address is valid: %s' % emailaddr)
if usecolor == 'color':
print('\n\033[36memail address is valid \033[0m\n')
else:
print('\nemail address is valid\n')
return emailformat
# END OF FUNCTION checkformat()
# FUNCTION TO PARSE MULTIPART EMAIL PAYLOAD
def decode_email(msg):
text = ""
att = False
html = None
pars = msg.get_payload()
pars = str(msg)
msgdir = dir(msg)
parsdir = dir(pars)
msgwalk = msg.walk()
headers = Parser().parsestr(pars)
wa = [x for x in (msgdir, parsdir, msgwalk, headers)]
print(wa)
if type(msg) is str:
parsed = msg
print('\n***DEBUG: returning msg as parsed\n')
return parsed # nothing more to parse
elif msg.get_payload() is None:
print('\n***DEBUG: returning msg as NoneType\n')
return msg
else:
decoded = msg.get_payload()
if decoded is None:
print('\n***DEBUG: returning decoded as NoneType\n')
return msg
msgfrom = ''
mdate = ''
msgto = ''
msgsubject = ''
if msg['From']:
msgfrom = msg['From']
msgfrom = msgfrom.replace('/', '-')
msgfrom = msgfrom.replace('<', ' ')
msgfrom = msgfrom.replace('>', '')
mdate = msg['Date']
msgto = completed[-1]
if msgto:
print('completed email: %s \n' % str(msgto))
else:
msgto = msg['Envelope-to']
print('env to: %s \n' % str(msgto))
msgid = msg['Email-id']
if msgto is None:
msgto = msg['To']
print('msg to: %s \n' % str(msgto))
if msgto is None:
msgto = msg['Cc']
print('msg cc: %s \n' % str(msgto))
if msgto is None:
msgto = msg['Bcc']
print('msg bcc: %s \n' % str(msgto))
if msgto is None:
msgto = headers['To']
print('msg bcc: %s \n' % str(msgto))
if msgto is None:
msgto = 'none@unknown.com'
msgto = msgto.replace('/', '-')
msgto = msgto.replace('<', ' ')
msgto = msgto.replace('>', '')
msgto = str(msgto)
msgdate = mdate[5:][:11]
if msg['Subject']:
msgsubject = msg['Subject'].replace('/', '-')
else:
msgsubject = 'No Subject'
rootdir = savedir
atdomain = re.search("@.*", msgto).group()
emaildomain = str(atdomain[1:])
j = len(msgto) - len(atdomain)
user_save = msgto[:j]
subdir = user_save + "_" + emaildomain
save_path = os.path.join(rootdir, subdir)
if not os.path.exists(save_path):
os.makedirs(save_path)
att_dir = os.path.join(save_path, 'attachments')
if not os.path.exists(att_dir):
os.makedirs(att_dir)
print('\nDEBUG: returning decoded as text \n')
decoded = msg.get_payload()
content_type = msg.get_content_type()
multitypes = ['multipart', 'alternative', 'application', 'related']
charset = msg.get_content_charset()
print("\033[32mContent-Type: %s \nCharset: %s \n\033[0m" % (content_type, charset))
# plain text format
if content_type == 'text/plain':
decoded = unicode(msg.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
enc = msg['Content-Transfer-Encoding']
if enc == "base64":
decoded = msg.get_payload()
decoded = base64.decodestring(decoded)
# rich text/html format
elif content_type == 'text/html':
decoded = unicode(msg.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
if any(x in content_type for x in multitypes):
print("\033[35m***DEBUG*** \n\033[33mLINE 607: MULTITYPE: %s \n\033[0m" % content_type)
att = True
n = 0
lim = len(decoded) - 1
attfile = msg.get_filename()
attachment = msg.get_payload(decode=True)
if attfile is None:
attfile = decoded[n].get_filename()
attachment = decoded[n].get_payload()
att_contype = decoded[n].get_content_type()
else:
att_contype = msg.get_content_type()
print("***DEBUG*** \n\033[36mLINE 616 \n\033[31mLIMIT: %d \033[0m \nATTACHMENT FILE: %s \n\n" % (lim, attfile))
while attfile is None and n < lim:
n += 1
attfile = decoded[n].get_filename()
print("***DEBUG*** \nDECODED ATTACHMENT FILE #%d: %s \n\n" % (n, attfile))
attachment = decoded[n].get_payload()
att_contype = decoded[n].get_content_type()
if 'multipart' in att_contype:
for att in attachment:
att_data = att.get_payload(decode=True)
att_type = att.get_content_type()
if 'plain' in att_type:
att_name = msgfrom + '-' + msgsubject + '.txt'
elif 'html' in att_type:
att_name = msgfrom + '-' + msgsubject + '.html'
else:
att_name = att.get_filename()
att_name = os.path.join(att_dir, str(att_name))
filename = att_name
if not os.path.isfile(filename):
try:
writedata = open(filename, 'wb+')
writedata.write(att_data)
writedata.close()
print('\nsaved attachment (try #1): %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except:
pass
try:
writedata = open(filename, 'wb+')
writedata.write(att.get_payload())
writedata.close()
print('\nsaved attachment (try #2): %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except e:
print('\nan error has occurred: %s \n' % str(e))
logging.error('an error occurred while trying to write file %s: %s' % (filename, str(e)))
else:
if 'html' in att_contype:
att_name = msgfrom + '-' + msgsubject + '-' + msgdate + '.html'
elif 'plain' in att_contype:
att_name = msgfrom + '-' + msgsubject + '-' + msgdate + '.txt'
else:
att_name = msgfrom + '-' + msgsubject + '-' + attfile
filename = os.path.join(att_dir, str(att_name))
if not os.path.isfile(filename):
try:
writedata = open(filename, 'wb+')
writedata.write(attachment)
writedata.close()
print('\n\033[31m**attachment saved to file successfully*** \033[0m \nFILE LOCATION: %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except:
pass
print('\n***skipped exception, MOVING ON.. \n')
logging.warning('passed exception trying to save %s. trying again..' % filename)
try:
writedata = open(filename, 'wb+')
writedata.write(attachment.get_payload())
writedata.close()
print('\nsaved attachment: %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except e:
print('\nan error has occurred: %s \n' % str(e))
logging.error('an error occurred while trying to write file %s: %s' % (filename, str(e)))
if attfile is None:
filename = msgfrom + '-' + msgsubject + '-' + msgdate + '.txt'
else:
filename = msgsubject + '-' + str(attfile)
filename = os.path.join(att_dir, filename)
if not os.path.isfile(filename):
try:
writedata = open(filename, 'wb+')
writedata.write(attachment)
writedata.close()
print('\nsaved attachment: %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except:
pass
try:
writedata = open(filename, 'wb+')
writedata.write(attachment.get_payload(decode=True))
writedata.close()
print('\n***DEBUG*** \nLINE 788: \nsaved attachment: %s \n' % filename)
logging.info('saved attachment: %s' % filename)
except:
pass
logging.error('an error occurred while trying to write file %s' % filename)
else:
if usecolor == 'color':
print('\n\033[33m' + filename + '\033[0m already exists, skipping.. \n')
else:
print('\n' + filename + ' already exists, skipping.. \n')
logging.info('skipping existing file: %s' % filename)
else:
return decoded
for part in decoded:
filename = part.get_filename()
# get content type and character set
contype = part.get_content_type()
charset = part.get_content_charset()
print("\033[31mContent-Type: %s \nCharset: %s \n\033[0m" % (contype, charset))
if charset is None: # probably a file attachment theni
text = part.get_payload(decode=True)
continue
# plain text format
if part.get_content_type() == 'text/plain':
text = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
enc = part['Content-Transfer-Encoding']
if enc == "base64":
text = part.get_payload()
text = base64.decodestring(text)
# rich text/html format
elif part.get_content_type() == 'text/html':
html = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
elif part.get('Content-Disposition') is None:
continue
# p7s signature
elif part.get_content_type() == 'application/pkcs7-signature':
att = True
sigdata = part.get_payload(decode=True)
if sigdata is None:
sigdata = part.get_payload()
signame = 'sig.p7s'
if part.get_filename() is None:
signame = msgfrom + '-' + msgsubject + '-' + msgdate + '.p7s'
else:
signame = msgfrom + '-' + msgdate + '-' + part.get_filename()
att_path = os.path.join(att_dir, signame)
sigfile = open(att_path, 'wb+')
sigfile.write(sigdata)
sigfile.close()
logging.info('saved signature file: %s' % signame)
print('saved signature file to disk: %s' % signame)
# message contains attachments
elif any(x in part.get_content_type() for x in multitypes):
att = True
# text of message
a = part.get_payload(0)
# attachments
b = part.get_payload(1)
# plain text message
if a.get_content_type() == 'text/plain':
text = a
if a['Content-Transfer-Encoding'] == 'base64':
text = a.get_payload()
text = base64.decodestring(text)
# html or rich-text format
elif a.get_content_type() == 'text/html':
html = unicode(a.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
# attachments
if part.get_filename() is not None:
file_name = part.get_filename()
complete_name = os.path.join(att_dir, file_name)
if not os.path.isfile(complete_name):
try:
attachment = part.get_payload()
partdata = open(complete_name, 'wb+')
partdata.write(attachment)
partdata.close()
print('\nsaved attachment: %s \n' % complete_name)
logging.info('saved attachment: %s' % complete_name)
except:
pass
try:
attachment = part.get_payload(decode=True)
partdata = open(complete_name, 'wb+')
partdata.write(attachment)
partata.close()
print('\nsaved attachment: %s \n' % complete_name)
logging.info('saved attachment: %s' % complete_name)
except e:
pass
print('\nan error has occurred while trying to save attachment %s: %s \n' % (complete_name,str(e)))
logging.error('an error occurred while trying to save attachment %s: %s' % (complete_name,str(e)))
elif "multipart" or "application" in b.get_content_type():
for bsub in b.get_payload():
bnext = bsub.get_payload(decode=True)
attachment = bnext
bname = bsub.get_filename()
if bname is None:
text = bnext
btype = bsub.get_content_type()
print('\nbtype:\n%s \n' % btype)
print('\ntext:\n%s \n' % text)
bname = msgfrom + '-' + msgsubject + '-' + msgdate + '.txt'
else:
bname = msgfrom + '-' + msgdate + '-' + bname
bfilename = os.path.join(att_dir, bname)
if bnext is None: # possibly more attachments within
try:
attachment = decode_email(bsub)
bdata = open(bfilename, 'wb+')
bdata.write(attachment)
bdata.close()
print('\nsaved attachment: %s \n' % bname)
logging.info('saved attachment: %s' % bname)
except:
pass
try:
attachment = bsub
bdata = open(bfilename, 'wb+')
bdata.write(attachment)
bdata.close()
print('\nsaved attachment: %s \n' % bname)
logging.info('saved attachment: %s' % bname)
except e:
print('\nan error has occurred: %s \n' % str(e))
logging.error('an error has occurred: %s' % str(e))
else:
try:
bdata = open(bfilename, 'wb+')
bdata.write(bnext)
bdata.close()
print('\nsaved attachment: %s \n' % bname)
logging.info('saved attachment: %s' % bname)
attachment = bnext
except e:
pass
print('\nan error has occurred: %s \n' % str(e))
logging.error('an error has occurred: %s' % str(e))
else:
text = part.get_payload(decode=True)
continue
# PGP encrypted message or attachment
elif part.get_content_type() == 'application/pgp-encrypted' or part.get_content_type() == 'application/octet-stream':
att = True
text = part.get_payload(decode=True)
for crypt in part.get_payload():
if type(crypt) is str:
text = crypt
att = False
continue
else:
enc = crypt['Content-Transfer-Encoding']
if crypt.get_content_type() == 'text/plain':
text = crypt.get_payload()
if 'base6s4' in enc:
text = base64.decodestring(text)
att = False
continue
elif crypt.get_content_type() == 'text/html':
html = unicode(crypt.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace').strip()
else:
att = True
cryptdata = crypt.get_payload(decode=True)
attachment = cryptdata
cryptname = crypt.get_filename()
if cryptname is None:
cryptname = msgfrom + ' - ' + msgsubject + ' - ' + '.gpg'
else:
cryptname = msgfrom + ' - ' + msgsubject + ' - ' + cryptname
att_path = os.path.join(att_dir, cryptname)
try:
if not os.path.exists(att_path):
cryptfile = open(att_path, 'wb+')
cryptfile.write(cryptdata)
cryptfile.close()
attfile = cryptfile
print('\n**********\nsaved attachment: %s \n' % cryptname)
logging.info('saved attachment: %s' % cryptname)
else:
cryptfile = open(att_path, 'rb+')
cryptdata = cryptfile.read()
print('\n%s exists, skipping... \n' % cryptname)
logging.info('%s exists, skipped..' % cryptname)
except e:
pass
print('\nan error has occurred: %s \n' % str(e))
logging.error('an error has occurred: %s' % str(e))
if 'use_gpg' not in locals():