Advertisement
eudemonics

EMAIL2FILE.PY -- huge update! requires ENCODELIST.PY

Apr 18th, 2015
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 44.39 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. ##### EMAIL2FILE v1.4 BETA
  4. ##### AUTHOR: vvn < vvn @ notworth dot it >
  5. ##### VERSION RELEASE: April 5, 2015
  6. ##### save email lists in plain text format in script directory with one address per line.
  7. ##### you can also include the password, if known. just use "email@addy.com, password" instead.
  8. ##### if there are only a few email addresses, you can easily generate the file:
  9. ##### open a terminal window to the script directory, then enter:
  10. ##### echo "your@email.com" >> emails.txt
  11. ##### repeat that command for each email you want to use, then enter "emails.txt" for the filename
  12. ##### word lists should be one word per line or you'll probably get some kind of format error.
  13. ##### TO RUN SCRIPT, open terminal to script directory and enter "python email2file.py"
  14. ##### PLEASE USE PYTHON 2.7+ AND NOT PYTHON 3 OR YOU WILL GET SYNTAX ERRORS.
  15. ##### works best on OSX and linux systems, but you can try it on windows.
  16. ##### i even tried to remove all the ANSI codes for you windows users, so you'd better use it!
  17. ##### even better, if you are on windows, install the colorama module for python to support ANSI
  18. ##### if you have setuptools or pip installed, you can easily get it with "pip install colorama"
  19. ##### each inbox message is saved as a txt file in its respective account's directory within the 'email-output' subdirectory of user home directory (or $HOME env path)
  20. ##### for example, example@email.com will output to a directory called 'example_email.com'
  21. ##### a file of all mail headers fetched from your inbox is also saved in the 'email-output' directory
  22. ##### it should be called example@email.com-headerlist-yyyy-mm-dd.txt
  23. ##### attachments are saved either in user folder or user's 'attachments' subfolder
  24. ##### questions? bugs? suggestions? contact vvn at: vvn@notworth.it
  25. ##### source code for stable releases should be available on my pastebin:
  26. ##### http://pastebin.com/u/eudemonics
  27. ##### or on github: http://github.com/eudemonics/email2file
  28. ##### git clone https://github.com/eudemonics/email2file.git email2file
  29. ##################################################
  30. ##################################################
  31. ##### USER LICENSE AGREEMENT & DISCLAIMER
  32. ##### copyright, copyleft (C) 2014-2015  vvn < vvn @ notworth . it >
  33. #####
  34. ##### This program is FREE software: you can use it, redistribute it and/or modify
  35. ##### it as you wish. Copying and distribution of this file, with or without modification,
  36. ##### are permitted in any medium without royalty provided the copyright
  37. ##### notice and this notice are preserved. This program is offered AS-IS,
  38. ##### WITHOUT ANY WARRANTY; without even the implied warranty of
  39. ##### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  40. ##### GNU General Public License for more details.
  41. ##################################################
  42. ##################################################
  43. ##### getting credited for my work is nice. so are donations.
  44. ##### BTC: 1M511j1CHR8x7RYgakNdw1iF3ike2KehXh
  45. ##### https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=26PWMPCNKN28L
  46. ##### but to really show your appreciation, you should buy my EP instead!
  47. ##### you can stream and purchase it at: dreamcorp.bandcamp.com
  48. ##### (you might even enjoy listening to it)
  49. ##### questions, comments, feedback, bugs, complaints, death threats, marriage proposals?
  50. ##### contact me at:
  51. ##### vvn (at) notworth (dot) it
  52. ##### there be only about a thousand lines of code after this -->
  53.  
  54. from __future__ import print_function
  55. import email, base64, getpass, imaplib, ast
  56. import re, sys, os, os.path, datetime, socket, time, traceback, logging
  57.  
  58. colorintro = '''
  59. \033[34m=====================================\033[33m
  60. ----------\033[36m EMAIL2FILE v1.4 \033[33m----------
  61. -------------------------------------
  62. -----------\033[35m author : vvn \033[33m------------
  63. ----------\033[32m vvn@notworth.it \033[33m----------
  64. \033[34m=====================================\033[33m
  65. ----\033[37m support my work: buy my EP! \033[33m----
  66. ---\033[37m http://dreamcorp.bandcamp.com \033[33m---
  67. ---\033[37m facebook.com/dreamcorporation \033[33m---
  68. ------\033[32m thanks for the support! \033[33m------
  69. \033[34m=====================================\n\033[0m
  70. '''
  71.  
  72. cleanintro = '''
  73. =====================================
  74. ---------- EMAIL2FILE v1.4 ----------
  75. -------------------------------------
  76. ----------- author : vvn ------------
  77. ---------- vvn@notworth.it ----------
  78. =====================================
  79. ---- support my work: buy my EP! ----
  80. --- http://dreamcorp.bandcamp.com ---
  81. --- facebook.com/dreamcorporation ---
  82. ------ thanks for the support! ------
  83. =====================================
  84. '''
  85.  
  86. global usecolor
  87.  
  88. if os.name == 'nt' or sys.platform == 'win32':
  89.    try:
  90.       import colorama
  91.       colorama.init()
  92.       usecolor = "color"
  93.       progintro = colorintro
  94.    except:
  95.       try:
  96.          import tendo.ansiterm
  97.          usecolor = "color"
  98.          progintro = colorintro
  99.       except:
  100.          usecolor = "clean"
  101.          progintro = cleanintro
  102.          pass
  103. else:
  104.    usecolor = "color"
  105.    progintro = colorintro
  106.  
  107. print(progintro)
  108.  
  109. time.sleep(0.9)
  110.  
  111. # CHECK IF SINGLE EMAIL (1) OR LIST OF MULTIPLE EMAIL ADDRESSES IS USED (2)
  112. print('''SINGLE EMAIL ADDRESS OR LIST OF MULTIPLE EMAIL ADDRESSES?
  113. list of multiple email addresses must be in text format
  114. with one email address per line, with optional encoded password
  115. after a comma (example@domain.com, password)
  116. **CAN ALSO USE SEPARATE PASSWORD LIST**
  117. ''')
  118. qtyemail = raw_input('enter 1 for single email or 2 for multiple emails --> ')
  119.  
  120. while not re.search(r'^[12]$', qtyemail):
  121.    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 --> ')
  122.  
  123. usewordlist = raw_input('do you want to use a word list rather than supply a password? enter Y/N --> ')
  124.  
  125. while not re.search(r'^[nyNY]$', usewordlist):
  126.    usewordlist = raw_input('invalid entry. enter Y to use word list or N to supply password --> ')
  127.  
  128. usesslcheck = raw_input('use SSL? Y/N --> ')
  129.  
  130. while not re.search(r'^[nyNY]$', usesslcheck):
  131.    usesslcheck = raw_input('invalid selection. please enter Y for SSL or N for unencrypted connection. -->')
  132.  
  133. sslcon = 'yes'
  134.  
  135. if usesslcheck.lower() == 'n':
  136.    sslcon = 'no'
  137.  
  138. else:
  139.    sslcon = 'yes'
  140.  
  141. def checklogin(emailaddr, emailpass, sslcon):
  142.  
  143.    global checkresp
  144.    efmatch = re.search(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,9})$', emailaddr)
  145.    if efmatch:
  146.       if usecolor == 'color':
  147.          validmail = '\033[32m\nemail is valid: %s \033[0m\n' % emailaddr
  148.       else:
  149.          validmail = 'email is valid: %s ' % emailaddr
  150.       print(validmail)
  151.    else:
  152.       print('invalid email format, skipping..')
  153.       pass
  154.  
  155.    atdomain = re.search("@.*", emailaddr).group()
  156.    emaildomain = atdomain[1:]
  157.  
  158.    imap_server = 'imap.' + emaildomain
  159.    imap_port = 993
  160.  
  161.    if 'no' in sslcon:
  162.       imap_port = 143
  163.  
  164.       if 'gmail.com' in emaildomain:
  165.          imap_port = 587
  166.  
  167.    if 'yes' in sslcon:
  168.       server = imaplib.IMAP4_SSL(imap_server, imap_port)
  169.  
  170.    else:
  171.       server = imaplib.IMAP4(imap_server, imap_port)
  172.  
  173.    checkresp = 'preconnect'
  174.    logging.info('INFO: attempting to connect to IMAP server to check login credentials for account %s' % emailaddr)
  175.  
  176.    try:
  177.  
  178.       loginstatus, logindata = server.login(emailaddr, emailpass)
  179.  
  180.       if 'OK' in loginstatus:
  181.          print('LOGIN SUCCESSFUL: %s' % emailaddr)
  182.          logging.info('INFO: LOGIN successful for account %s' % emailaddr)
  183.          checkresp = 'OK'
  184.  
  185.       elif 'AUTHENTICATIONFAILED' in loginstatus:
  186.          loginmsg = 'LOGIN FAILED: %s with %s' % (loginstatus, logindata)
  187.          print(loginmsg)
  188.          logging.error('ERROR: %s' % loginmsg)
  189.          checkresp = 'AUTHENFAIL'
  190.  
  191.       elif 'PRIVACYREQUIRED' in loginstatus:
  192.          loginmsg = 'LOGIN FAILED: %s with %s' % (loginstatus, logindata)
  193.          print(loginmsg)
  194.          logging.error('ERROR: %s' % loginmsg)
  195.          checkresp = 'PRIVACYREQ'
  196.  
  197.       elif 'UNAVAILABLE' in loginstatus:
  198.          loginmsg = 'LOGIN FAILED: %s with %s' % (loginstatus, logindata)
  199.          print(loginmsg)
  200.          logging.error('ERROR: %s' % loginmsg)
  201.          checkresp = 'UNAVAIL'
  202.  
  203.       elif 'AUTHORIZATIONFAILED' in loginstatus:
  204.          loginmsg = 'LOGIN FAILED: %s with %s' % (loginstatus, logindata)
  205.          print(loginmsg)
  206.          logging.error('ERROR: %s' % loginmsg)
  207.          checkresp = 'AUTHORFAIL'
  208.  
  209.       elif 'EXPIRED' in loginstatus:
  210.          loginmsg = 'LOGIN FAILED: %s with %s' % (loginstatus, logindata)
  211.          print(loginmsg)
  212.          logging.error('ERROR: %s' % loginmsg)
  213.          checkresp = 'EXPIRED'
  214.  
  215.       elif 'CONTACTADMIN' in loginstatus:
  216.          loginmsg = 'LOGIN FAILED: %s' % loginstatus
  217.          print(loginmsg)
  218.          logging.error('ERROR: %s' % loginmsg)
  219.          checkresp = 'ADMINREQ'
  220.  
  221.       else:
  222.          print('Unable to connect: %s' % emailaddr)
  223.          logging.error('ERROR: %s' % loginstatus)
  224.          checkresp = 'UNKNOWN'
  225.          
  226.    except IOError as e:
  227.       pass
  228.       logging.error('IO ERROR: %s' % str(e))
  229.       checkresp = 'IOERROR'
  230.    
  231.    except socket.error as e:
  232.       pass
  233.       logging.error('SOCKET ERROR: %s' % str(e))
  234.       checkresp = 'SOCKETERROR'
  235.  
  236.    except server.error as e:
  237.       pass
  238.       logging.error('IMAPLIB ERROR: %s' % str(e))
  239.       checkresp = 'IMAPERROR'
  240.  
  241.       if 'BAD' in str(e):
  242.          checkresp = 'BAD'
  243.       else:
  244.          checkresp = 'ERROR'
  245.  
  246.    except socket.timeout as e:
  247.       pass
  248.       print('Socket timeout: %s' % str(e))
  249.       logging.error('ERROR: Socket timeout')
  250.       checkresp = 'TIMEOUT'
  251.  
  252.    return checkresp
  253. # END OF FUNCTION checklogin()
  254.  
  255. # FUNCTION TO CHECK FOR EMAIL FORMAT ERRORS BEFORE SUBMITTING TO SERVER
  256. def checkformat(emailaddr):
  257.  
  258.    # START WHILE LOOP TO CHECK EMAIL FORMAT FOR ERRORS BEFORE ATTEMPTING LOGIN
  259.    match = re.search(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,9})$', emailaddr)
  260.    while not match:
  261.       emailformat = 'bad'
  262.       if usecolor == 'color':
  263.          print('\033[31m invalid email format \033[0m\n')
  264.       else:
  265.          print('invalid email format')
  266.       emailaddr = raw_input('please enter email again --> ')
  267.       emailpass = getpass.getpass('please enter password --> ')
  268.  
  269.    emailformat = 'good'
  270.    return emailformat
  271. # END OF FUNCTION checkformat()
  272.  
  273. # FUNCTION TO DECODE EMAIL BODY AND ATTACHMENTS
  274. def decode_email(msgbody):
  275.  
  276.    msg = email.message_from_string(msgbody)
  277.  
  278.    if msg is None:
  279.       decoded = msg
  280.  
  281.    decoded = msg
  282.    text = ""
  283.    att = False
  284.  
  285.    if msg.is_multipart():
  286.       html = None
  287.  
  288.       for part in msg.get_payload():
  289.  
  290.          print("\033[31m%s, %s\033[0m" % (part.get_content_type(), part.get_content_charset()))
  291.  
  292.          if part.get_content_charset() is None:
  293.             text = part.get_payload(decode=True)
  294.             continue
  295.  
  296.          charset = part.get_content_charset()
  297.  
  298.          if part.get_content_type() == 'text/plain':
  299.             text = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')
  300.             enc = part['Content-Transfer-Encoding']
  301.             if enc == "base64":
  302.                text = part.get_payload()
  303.                text = base64.decodestring(text)
  304.  
  305.          if part.get_content_type() == 'text/html':
  306.             html = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')
  307.  
  308.          if part.get_content_maintype() == 'multipart':
  309.             continue
  310.  
  311.          elif part.get('Content-Disposition') is None:
  312.             continue
  313.  
  314.          elif part.get_content_type() == "multipart/alternative":
  315.             text = part.get_payload(decode=True)
  316.             enc = part['Content-Transfer-Encoding']
  317.             if part.get_content_type() == "text/plain":
  318.                 text = part.get_payload()
  319.                 if enc == "base64":
  320.                     text = base64.decodestring(text)
  321.  
  322.          filename = part.get_filename()
  323.  
  324.          if bool(filename):
  325.  
  326.             homedir = os.path.expanduser("~")
  327.  
  328.             rootdir = os.path.join(homedir, 'email-output')
  329.  
  330.             if not os.path.exists(rootdir):
  331.                os.makedirs(rootdir, 0755)
  332.  
  333.             atdomain = re.search("@.*", emailaddr).group()
  334.             emaildomain = atdomain[1:]
  335.             i = len(emailaddr) - len(atdomain)
  336.             user_savename = emailaddr[:i]
  337.             # user_savename = emailaddr.rstrip(atdomain)
  338.             subdir = user_savename+"_"+emaildomain
  339.  
  340.             detach_dir = os.path.join(rootdir, subdir)
  341.  
  342.             if not os.path.exists(detach_dir):
  343.                os.makedirs(detach_dir, 0755)
  344.  
  345.             att_path = os.path.join(detach_dir, 'attachments', filename)
  346.  
  347.             if 'attachments' not in os.listdir(detach_dir):
  348.                os.makedirs(detach_dir + '/attachments', 0755)
  349.  
  350.             att = True
  351.  
  352.             if not os.path.isfile(att_path):
  353.                attfile = open(att_path, 'wb+')
  354.                attfile.write(part.get_payload(decode=True))
  355.                attfile.close()
  356.                decoded = attfile
  357.  
  358.       if att is False:
  359.          decoded = msg
  360.  
  361.          if html is None and text is not None:
  362.             decoded = text.strip()
  363.  
  364.          elif html is None and text is None:
  365.             decoded = msg
  366.  
  367.          else:
  368.             decoded = html.strip()
  369.  
  370.    else:
  371.       decoded = msg
  372.  
  373.    return decoded
  374. # END OF FUNCTION decode_email()
  375.  
  376. # FUNCTION TO LOG ONTO IMAP SERVER FOR SINGLE EMAIL ADDRESS
  377. def getimap(emailaddr, emailpass, sslcon):
  378.  
  379.    atdomain = re.search("@.*", emailaddr).group()
  380.    emaildomain = atdomain[1:]
  381.  
  382.    imap_server = 'imap.' + emaildomain
  383.    imap_port = 993
  384.    server = imaplib.IMAP4_SSL(imap_server, imap_port)
  385.  
  386.    if 'no' in sslcon:
  387.       imap_port = 143
  388.  
  389.    if 'gmail.com' in atdomain and 'no' in sslcon:
  390.       imap_port = 587
  391.  
  392.    if 'yes' in sslcon:
  393.       server = imaplib.IMAP4_SSL(imap_server, imap_port)
  394.  
  395.    else:
  396.       server = imaplib.IMAP4(imap_server, imap_port)
  397.  
  398.    attempts = 20
  399.  
  400.    while True and attempts > 0:
  401.  
  402.       try:
  403.  
  404.          loginstatus, logindata = server.login(emailaddr, emailpass)
  405.  
  406.          if loginstatus == 'OK':
  407.  
  408.             select_info = server.select('INBOX')
  409.             status, unseen = server.search(None, 'UNSEEN')
  410.             typ, listdata = server.list()
  411.             countunseen = len(unseen)
  412.  
  413.             if usecolor == 'color':
  414.  
  415.                print("\n\033[35m%d UNREAD MESSAGES\033[0m" % len(unseen))
  416.                print()
  417.                print('Response code: \n\033[32m', typ)
  418.                print('\033[0m\nFOLDERS:\n\033[33m', listdata)
  419.                print('\033[34m\nlogin successful, fetching emails.. \033[0m\n')
  420.  
  421.             else:
  422.  
  423.                print("%d UNREAD MESSAGES" % len(unseen))
  424.                print()
  425.                print('Response code: \n', typ)
  426.                print('\nFOLDERS:\n', listdata)
  427.                print('\nlogin successful, fetching emails.. \n')
  428.  
  429.             logging.info('INFO: LOGIN successful for %s.' % emailaddr)
  430.             logging.info('INFO: %d unread messages.' % countunseen)
  431.             logging.info('INFO: fetching all messages...')
  432.  
  433.             # server.list()
  434.  
  435.             server.select()
  436.  
  437.             result, msgs = server.search(None, 'ALL')
  438.  
  439.             ids = msgs[0]
  440.             id_list = ids.split()
  441.  
  442.             print(id_list)
  443.  
  444.             if usecolor == 'color':
  445.  
  446.                print('\033[37m------------------------------------------------------------\n\033[0m')
  447.  
  448.             else:
  449.  
  450.                print('------------------------------------------------------------')
  451.  
  452.  
  453.             homedir = os.path.expanduser("~")
  454.  
  455.             rootdir = os.path.join(homedir, 'email-output')
  456.  
  457.             if not os.path.exists(rootdir):
  458.                os.makedirs(rootdir, 0755)
  459.  
  460.             printdate = str(datetime.date.today())
  461.  
  462.             prev_file_name = emailaddr+"-headerlist-"+printdate+".txt"
  463.             prev_complete_name = os.path.join(rootdir, prev_file_name)
  464.  
  465.             for email_uid in id_list:
  466.  
  467.                result, rawdata = server.fetch(email_uid, '(RFC822)')
  468.  
  469.                rawbody = rawdata[0][1]
  470.  
  471.                m = email.message_from_string(rawbody)
  472.  
  473.                msgfrom = m['From'].replace('/', '-')
  474.  
  475.                body = decode_email(rawbody)
  476.  
  477.                emaildomain = atdomain[1:]
  478.                j = len(emailaddr) - len(atdomain)
  479.                user_save = emailaddr[:j]
  480.  
  481.                subdir =  user_save + "_" + emaildomain
  482.                save_path = os.path.join(rootdir, subdir)
  483.  
  484.                if not os.path.exists(save_path):
  485.                   os.makedirs(save_path)
  486.  
  487.                mbody = email.message_from_string(rawbody)
  488.  
  489.                if mbody.is_multipart():
  490.  
  491.                   ext = ".txt"
  492.  
  493.                   for mpart in mbody.get_payload():
  494.  
  495.                      if 'text' in mpart.get_content_type():
  496.                         ext = ".txt"
  497.                         isattach = False
  498.  
  499.                         if mpart.get_content_type() == 'text/html':
  500.                            ext = ".htm"
  501.                            isattach = False
  502.  
  503.                      else:
  504.                         file_name = mpart.get_filename()
  505.                         isattach = True
  506.  
  507.                else:
  508.                   isattach = False
  509.                   ext = ".txt"
  510.  
  511.                if isattach is False:
  512.                   file_name = user_save + "-" + email_uid + "-" + msgfrom[:35] + ext
  513.  
  514.                if file_name is None:
  515.                   file_name = user_save + "-" + msgfrom[:35] + "-" + email_uid + ext
  516.  
  517.                complete_name = os.path.join(save_path, file_name)
  518.  
  519.                dtnow = datetime.datetime.now()
  520.                dtyr = str(dtnow.year)
  521.                dtmo = str(dtnow.month)
  522.                dtday = str(dtnow.day)
  523.                dthr = str(dtnow.hour)
  524.                dtmin = str(dtnow.minute)
  525.  
  526.                dtdate = str(dtyr + "-" + dtmo + "-" + dtday)
  527.                dttime = str(dthr + "." + dtmin)
  528.  
  529.                if os.path.isfile(complete_name):
  530.  
  531.                   print('\n\033[33m' + complete_name + '\033[0m already exists, skipping.. \n')
  532.  
  533.                else:
  534.  
  535.                   if type(body) is str or type(body) is buffer and isattach is True:
  536.                      print('\n\033[34mdownloading file: \033[33m' + str(file_name) + '\033[0m\n')
  537.                      bodyfile = open(complete_name, 'wb+')
  538.                      # bodyfile.seek(0)
  539.                      bodyfile.write(body)
  540.                      bodyfile.close()
  541.  
  542.                   else:
  543.                      bodyfile = open(complete_name, 'wb+')
  544.                      bodyfile.write("SENDER: \n")
  545.                      bodyfile.write(msgfrom)
  546.                      bodyfile.write('\n')
  547.                      # bodyfile.write('Decoded:\n')
  548.                      bodyfile.write(str(body))
  549.                      bodyfile.write('\nRAW MESSAGE DATA:\n')
  550.                      bodyfile.write(rawbody)
  551.                      bodyfile.write('\n')
  552.                      bodyfile.write('file saved: ' + dtdate + ', ' + dttime)
  553.                      bodyfile.write('\n')
  554.                      bodyfile.close()
  555.  
  556.                   if usecolor == 'color':
  557.  
  558.                      print('\033[36m\033[1mmessage data saved to new file: \033[35m' + complete_name + '\033[0m\n')
  559.  
  560.                   else:
  561.  
  562.                      print('message data saved to new file: ' + complete_name)
  563.  
  564.                if usecolor == 'color':
  565.  
  566.                   print('\033[37m------------------------------------------------------------\033[0m\n')
  567.  
  568.                   resp, data = server.fetch(email_uid, '(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
  569.                   print('\033[35m' + email_uid + '\033[0m\n')
  570.  
  571.                else:
  572.  
  573.                   print('------------------------------------------------------------\n')
  574.  
  575.                   resp, data = server.fetch(email_uid, '(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
  576.                   print(email_uid)
  577.  
  578.                print(data[0][1] + '\n')
  579.                msgpreview = data[0][1]
  580.  
  581.                if not os.path.isfile(prev_complete_name):
  582.                   prevfile = open(prev_complete_name, 'wb+')
  583.                #   prevfile.write('Email headers for: ' + emailaddr + '\n')
  584.                #   prevfile.close()
  585.  
  586.                with open(prev_complete_name, 'a+b') as prevfile:
  587.                   prevfile.write(email_uid)
  588.                   prevfile.write("\n")
  589.                   prevfile.write(msgpreview)
  590.                   prevfile.write("\n")
  591.                   # prevfile.close()
  592.  
  593.             if usecolor == 'color':
  594.  
  595.                print('\033[32minbox contents successfully saved to file. YAY! \033[0m\n')
  596.  
  597.             else:
  598.  
  599.                print('inbox contents successfully saved to file. YAY!')
  600.  
  601.          if usecolor == 'color':
  602.  
  603.             print('list of message previews saved as: \033[31m' + prev_complete_name + '\033[0m \n')
  604.  
  605.          else:
  606.  
  607.             print('list of message previews saved as: ', prev_complete_name)
  608.  
  609.          print('logging out..\n')
  610.  
  611.          server.logout()
  612.  
  613.          print('logout successful. exiting..\n')
  614.          attempts = -1
  615.          break
  616.  
  617.       except server.error as e:
  618.          pass
  619.          logging.error('IMAPLIB ERROR: %s' % str(e))
  620.          checkresp = 'ERROR'
  621.  
  622.          if usecolor == 'color':
  623.             print('\033[32mconnection failed to IMAP server.\033[0m\n')
  624.             print('\033[36mIMAPLIB ERROR: \033[33m' + str(e) + '\033[0m\n')
  625.  
  626.          else:
  627.  
  628.             print('connection failed to IMAP server.\n')
  629.             print('IMAPLIB ERROR: ' + str(e) + '\n')
  630.  
  631.          if qtyemail == '1':
  632.  
  633.             attempts = attempts - 1
  634.             emailaddr = raw_input('please enter email again --> ')
  635.             emailpass = getpass.getpass('please enter password --> ')
  636.  
  637.             matchaddy = re.search(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,9})$', emailaddr)
  638.  
  639.             while not matchaddy and attempts > 1:
  640.                print('\033[31m invalid email format \033[0m\n')
  641.                attempts = attempts - 1
  642.  
  643.             getimap(emailaddr, emailpass, sslcon)
  644.             continue
  645.  
  646.    if attempts is 0:
  647.       print('too many logon failures. unable to log onto IMAP server. quitting..')
  648.       sys.exit()
  649. # END OF FUNCTION getimap(emailaddr, emailpass, sslcon)
  650.  
  651. # FUNCTION FOR IMAP CONNECTION USING MULTIPLE ADDRESSES
  652. def getimapmulti(emailaddr, emailpass, sslcon):
  653.  
  654.    atdomain = re.search("@.*", emailaddr).group()
  655.    emaildomain = atdomain[1:]
  656.  
  657.    imap_server = 'imap.' + emaildomain
  658.    imap_port = 993
  659.  
  660.    if 'no' in sslcon:
  661.       imap_port = 143
  662.  
  663.       if 'gmail.com' in emaildomain:
  664.          imap_port = 587
  665.  
  666.    server = imaplib.IMAP4_SSL(imap_server, imap_port)
  667.  
  668.    if 'yes' in sslcon:
  669.       server = imaplib.IMAP4_SSL(imap_server)
  670.  
  671.    else:
  672.       server = imaplib.IMAP4(imap_server, imap_port)
  673.  
  674.    loginstatus, logindata = server.login(emailaddr, emailpass)
  675.  
  676.    attempts = 0
  677.  
  678.    while attempts <= 20:
  679.  
  680.       try:
  681.          select_info = server.select('INBOX')
  682.          status, unseen = server.search(None, 'UNSEEN')
  683.  
  684.          typ, listdata = server.list()
  685.  
  686.          countunseen = len(unseen)
  687.  
  688.          if usecolor == 'color':
  689.  
  690.             print("\n\033[35m%d UNREAD MESSAGES\033[0m" % len(unseen))
  691.             print()
  692.             print('Response code: \n\033[32m', typ)
  693.             print('\033[0m\nFOLDERS:\n\033[33m', listdata)
  694.             print('\033[34m\nlogin successful, fetching emails.. \033[0m\n')
  695.  
  696.          else:
  697.  
  698.             print("%d UNREAD MESSAGES" % len(unseen))
  699.             print()
  700.             print('Response code: \n', typ)
  701.             print('\nFOLDERS:\n', listdata)
  702.             print('\nlogin successful, fetching emails.. \n')
  703.  
  704.          server.select()
  705.          result, msgs = server.search(None, 'ALL')
  706.  
  707.          ids = msgs[0]
  708.          id_list = ids.split()
  709.  
  710.          print(id_list)
  711.  
  712.          if usecolor == 'color':
  713.  
  714.             print('\033[37m------------------------------------------------------------\n\033[0m')
  715.  
  716.          else:
  717.  
  718.             print('------------------------------------------------------------')
  719.  
  720.          homedir = os.path.expanduser("~")
  721.  
  722.          rootdir = os.path.join(homedir, 'email-output')
  723.  
  724.          if not os.path.exists(rootdir):
  725.             os.makedirs(rootdir, 0755)
  726.  
  727.          printdate = str(datetime.date.today())
  728.  
  729.          prev_file_name = emailaddr+"-headerlist-"+printdate+".txt"
  730.          prev_complete_name = os.path.join(rootdir, prev_file_name)
  731.  
  732.          for email_uid in id_list:
  733.  
  734.             result, rawdata = server.fetch(email_uid, '(RFC822)')
  735.  
  736.             rawbody = rawdata[0][1]
  737.  
  738.             m = email.message_from_string(rawbody)
  739.  
  740.             msgfrom = m['From'].replace('/', '-')
  741.  
  742.             body = decode_email(rawbody)
  743.  
  744.             emaildomain = atdomain[1:]
  745.             j = len(emailaddr) - len(atdomain)
  746.             user_save = emailaddr[:j]
  747.  
  748.             subdir =  user_save + "_" + emaildomain
  749.             save_path = os.path.join(rootdir, subdir)
  750.  
  751.             if not os.path.exists(save_path):
  752.                os.makedirs(save_path)
  753.  
  754.             mbody = email.message_from_string(rawbody)
  755.  
  756.             if mbody.is_multipart():
  757.  
  758.                ext = ".txt"
  759.  
  760.                for mpart in mbody.get_payload():
  761.  
  762.                   if 'text' in mpart.get_content_type():
  763.                      ext = ".txt"
  764.                      isattach = False
  765.  
  766.                      if mpart.get_content_type() == 'text/html':
  767.                         ext = ".htm"
  768.                         isattach = False
  769.  
  770.                   else:
  771.                      file_name = mpart.get_filename()
  772.                      isattach = True
  773.  
  774.             else:
  775.                isattach = False
  776.                ext = ".txt"
  777.  
  778.             if isattach is False:
  779.                file_name = user_save + "-" + email_uid + "-" + msgfrom[:25] + ext
  780.  
  781.             if file_name is None:
  782.                file_name = user_save + "-" + msgfrom[:25] + "-" + email_uid + ext
  783.  
  784.             complete_name = os.path.join(save_path, file_name)
  785.  
  786.             dtnow = datetime.datetime.now()
  787.             dtyr = str(dtnow.year)
  788.             dtmo = str(dtnow.month)
  789.             dtday = str(dtnow.day)
  790.             dthr = str(dtnow.hour)
  791.             dtmin = str(dtnow.minute)
  792.  
  793.             dtdate = str(dtyr + "-" + dtmo + "-" + dtday)
  794.             dttime = str(dthr + "." + dtmin)
  795.  
  796.             if os.path.isfile(complete_name):
  797.  
  798.                if usecolor == 'color':
  799.  
  800.                   print('\n\033[33m' + complete_name + '\033[0m already exists, skipping.. \n')
  801.  
  802.                else:
  803.  
  804.                   print(complete_name + 'already exists, skipping.. \n')
  805.  
  806.             else:
  807.  
  808.                if type(body) is str or type(body) is buffer and isattach is True:
  809.  
  810.                   if usecolor == 'color':
  811.                      print('\n\033[34mdownloading file: \033[33m' + str(file_name) + '\033[0m\n')
  812.  
  813.                   else:
  814.                      print('downloading file: ' + str(file_name))
  815.  
  816.                   bodyfile = open(complete_name, 'wb+')
  817.                   # bodyfile.seek(0)
  818.                   bodyfile.write(body)
  819.                   bodyfile.close()
  820.  
  821.                else:
  822.                   bodyfile = open(complete_name, 'wb+')
  823.                   bodyfile.write("SENDER: \n")
  824.                   bodyfile.write(msgfrom)
  825.                   bodyfile.write('\n')
  826.                   # bodyfile.write('Decoded:\n')
  827.                   bodyfile.write(str(body))
  828.                   bodyfile.write('\nRAW MESSAGE DATA:\n')
  829.                   bodyfile.write(rawbody)
  830.                   bodyfile.write('\n')
  831.                   bodyfile.write('file saved: ' + dtdate + ', ' + dttime)
  832.                   bodyfile.write('\n')
  833.                   bodyfile.close()
  834.  
  835.                if usecolor == 'color':
  836.  
  837.                   print('\033[36m\033[1mmessage data saved to new file: \033[35m' + complete_name + '\033[0m\n')
  838.  
  839.                else:
  840.  
  841.                   print('message data saved to new file: ' + complete_name)
  842.  
  843.             if usecolor == 'color':
  844.  
  845.                print('\033[37m------------------------------------------------------------\033[0m\n')
  846.  
  847.                resp, data = server.fetch(email_uid, '(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
  848.                print('\033[35m' + email_uid + '\033[0m\n')
  849.  
  850.             else:
  851.  
  852.                print('------------------------------------------------------------\n')
  853.  
  854.                resp, data = server.fetch(email_uid, '(UID FLAGS BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
  855.                print(email_uid)
  856.  
  857.             print(data[0][1] + '\n')
  858.             msgpreview = data[0][1]
  859.  
  860.             if not os.path.isfile(prev_complete_name):
  861.                prevfile = open(prev_complete_name, 'wb+')
  862.             #   prevfile.write('Email headers for: ' + emailaddr + '\n')
  863.             #   prevfile.close()
  864.  
  865.             with open(prev_complete_name, 'a+b') as prevfile:
  866.                prevfile.write(email_uid)
  867.                prevfile.write("\n")
  868.                prevfile.write(msgpreview)
  869.                prevfile.write("\n")
  870.                # prevfile.close()
  871.  
  872.          if usecolor == 'color':
  873.  
  874.             print('\033[32minbox contents successfully saved to file. YAY! \033[0m\n')
  875.  
  876.          else:
  877.  
  878.             print('inbox contents successfully saved to file. YAY!')
  879.  
  880.          if usecolor == 'color':
  881.             print('list of message previews saved as: \033[31m' + prev_complete_name + '\033[0m \n')
  882.          else:
  883.             print('list of message previews saved as: %s' % prev_complete_name)
  884.  
  885.          logging.info('INFO: inbox contents saved to file with preview file %s' % prev_complete_name)
  886.          print('logging out..\n')
  887.          logging.info('INFO: logging off IMAP server.')
  888.          server.logout()
  889.          if usecolor == 'color':
  890.             print('logout successful for \033[38m%s.\033[0m\n' % emailaddr)
  891.             print('\033[34m------------------------------------------------------------\033[0m\n')
  892.          else:
  893.             print('logout successful for %s.\n' % emailaddr)
  894.             print('------------------------------------------------------------\n')
  895.          logging.info('INFO: logout successful for %s.' % emailaddr)
  896.          checkresp = 'OK'
  897.          attempts = 100
  898.          break
  899.          
  900.       except IOError as e:
  901.          pass
  902.          print("IO SOCKET ERROR: %s" % str(e))
  903.          logging.error('IO SOCKET ERROR: %s' % str(e))
  904.          traceback.print_exc()
  905.          checkresp = 'IOERROR'
  906.          attempts += 1
  907.          
  908.       except socket.error as e:
  909.          pass
  910.          print("SOCKET ERROR: %s" % str(e))
  911.          traceback.print_exc()
  912.          logging.error('SOCKET ERROR: %s' % str(e))
  913.          checkresp = 'SOCKETERROR'
  914.          attempts += 1
  915.          continue
  916.      
  917.       except socket.timeout as e:
  918.          pass
  919.          print('Socket timeout: %s, retrying connection..' % str(e))
  920.          time.sleep(5.0)
  921.          checkresp = 'TIMEOUT'
  922.          attempts += 1
  923.          continue
  924.      
  925.       except TypeError as e:
  926.          pass
  927.          print("TYPE ERROR: %s" % e)
  928.          logging.error('TYPE ERROR: %s' % e)
  929.          checkresp = 'TYPEERROR'
  930.          attempts += 1
  931.          continue
  932.  
  933.       except server.error as e:
  934.          pass
  935.          logging.error('ERROR: %s' % e)
  936.          checkresp = 'ERROR'
  937.          attempts += 1
  938.          if usecolor == 'color':
  939.             print('\033[35mfailed connecting to IMAP server.\033[0m\n')
  940.             print('\033[31mERROR: \033[33m' + str(e) + '\033[0m\n')
  941.          else:
  942.             print('failed connecting to IMAP server.\n')
  943.             print('ERROR: ' + str(e) + '\n')
  944.            
  945.          if qtyemail == '1':
  946.             while True and attempts <= 20:
  947.                emailaddr = raw_input('please enter email again --> ')
  948.                emailpass = getpass.getpass('please enter password --> ')
  949.                checkformat(emailaddr)
  950.                logging.info('INFO: trying again with user-supplied email %s' % emailaddr)
  951.                print('RETRYING with %s..' % emailaddr)
  952.                pass
  953.                
  954.          # start with a socket at 30-second timeout
  955.          sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  956.          sock.settimeout(30.0)
  957.  
  958.          # check and turn on TCP Keepalive
  959.          x = sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
  960.          if( x == 0):
  961.             print('Socket KEEPALIVE off, turning on')
  962.             x = sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  963.             logging.info('INFO: setsockopt=', x)
  964.          else:
  965.             print('Socket Keepalive already on')
  966.             logging.info('INFO: Socket KEEPALIVE already on')
  967.  
  968.          try:
  969.             sock.connect(imap_server, imap_port)
  970.  
  971.          except socket.error:
  972.             print('Socket connection failed')
  973.             traceback.print_exc()
  974.             time.sleep(5.0)
  975.             continue
  976.  
  977.          print('Socket connection established!')
  978.  
  979.          while 1:
  980.             try:
  981.                 req = sock.recv(6)
  982.  
  983.             except socket.timeout:
  984.                 print('Socket timeout, retrying connection..')
  985.                 time.sleep( 5.0)
  986.                 # traceback.print_exc()
  987.                 continue
  988.  
  989.             except:
  990.                 traceback.print_exc()
  991.                 print('Other Socket error. Trying to recreate socket..')
  992.                 # break from loop
  993.                 break
  994.  
  995.             print('received ', req)
  996.  
  997.          try:
  998.             sock.close()
  999.          except:
  1000.             pass
  1001.          continue
  1002.      
  1003.       return checkresp
  1004. # END OF FUNCTION getimapmulti(emailaddr, emailpass, sslcon)
  1005.  
  1006. # MULTIPLE EMAIL ADDRESSES
  1007. if qtyemail == '2':
  1008.    emaillistfile = raw_input('please copy the email list file to the script directory, then enter filename --> ')
  1009.    while not os.path.isfile(emaillistfile):
  1010.       emaillistfile = raw_input('the file path specified does not exist or is not accessible. please check the file and enter again --> ')
  1011.  
  1012.    ef = open(emaillistfile, "r")
  1013.    emailfile = ef.readlines()
  1014.    eflen = len(emailfile)
  1015.  
  1016.    # USING PASSWORD LIST
  1017.    if usewordlist.lower() == 'y':
  1018.       pwlistfile = raw_input('please copy word list file to the script directory, then enter the filename --> ')
  1019.  
  1020.       while not os.path.isfile(pwlistfile):
  1021.          pwlistfile = raw_input('the path to the word list file you entered is not valid. please check the file and enter again --> ')
  1022.  
  1023.       b64sel = raw_input('is the word list base64-encoded? Y/N --> ')
  1024.  
  1025.       while not re.search(r'^[nNyY]$', b64sel):
  1026.          b64sel = raw_input('invalid selection. enter Y if word list is base64-encoded or N if plain text --> ')
  1027.  
  1028.       if b64sel.lower() == 'n':
  1029.  
  1030.          gotoencsel = raw_input('storing passwords in plaintext is a security risk. would you like to base64-encode your password list? Y/N --> ')
  1031.  
  1032.          while not re.search(r'^[yYnN]$', gotoencsel):
  1033.  
  1034.             gotoencsel = raw_input('invalid selection. enter Y to run script to encode a password list, or enter N to continue --> ')
  1035.  
  1036.          if gotoencsel.lower() == 'y':
  1037.             print('launching encodelist.py...')
  1038.             os.system('chmod +x encodelist.py')
  1039.             os.system('python encodelist.py')
  1040.  
  1041.          else:
  1042.             print('*** to base64-encode your list in the future, run \'python encpass.py\' ***')
  1043.  
  1044.       lnemail = ''
  1045.       lnpass = ''
  1046.  
  1047.       efcount = 0
  1048.       if usecolor == 'color':
  1049.          print("\n\033[31mEMAIL ADDRESSES IN FILE:\033[0m %s" % str(eflen))
  1050.       else:
  1051.          print("EMAIL ADDRESSES IN FILE: %s" % str(eflen))
  1052.  
  1053.       while efcount <= eflen:
  1054.  
  1055.          for line in emailfile:
  1056.  
  1057.             efcount += 1
  1058.  
  1059.             # WITH EMAIL AND PASSWORD IN SAME FILE
  1060.             if re.search(r'^[\,]$', line):
  1061.  
  1062.                line = line.strip()
  1063.                linevals = line.split(",")
  1064.  
  1065.                lnemail = linevals[0]
  1066.                lnemail = str(lnemail.strip())
  1067.                lnpass = linevals[1]
  1068.                if b64sel.lower() == 'y':
  1069.                   lnpass = base64.b64decode(lnpass)
  1070.  
  1071.                lnpass = lnpass.strip()
  1072.                lnpass = lnpass.replace("\n","")
  1073.                lnpass = str(lnpass)
  1074.  
  1075.                if usecolor == 'color':
  1076.                   print('\033[36musing email address: \033[0m' + lnemail)
  1077.                
  1078.                else:
  1079.                   print('using email address: ' + lnemail)
  1080.                  
  1081.                loginok = checklogin(lnemail, lnpass, sslcon)
  1082.  
  1083.                if 'OK' not in loginok:
  1084.                   print('login failure. skipping to next entry in list...')
  1085.                   logging.debug('DEBUG: LOGIN to %s failed' % emailaddr)
  1086.                   continue
  1087.                else:
  1088.                   logging.info('INFO: LOGIN to %s successful' % emailaddr)
  1089.                   getimapmulti(lnemail, lnpass, sslcon)
  1090.  
  1091.             else:
  1092.            
  1093.                if usecolor == 'color':
  1094.                   print('\033[38m------------------------------------------------------------\033[0m\n')
  1095.                   print('\n\033[36musing email address: \033[0m' + line)
  1096.                
  1097.                else:
  1098.                   print('------------------------------------------------------------\n')
  1099.                   print('\nusing email address: ' + line)
  1100.                  
  1101.                lnemail = line.strip()
  1102.                pf = open(pwlistfile, "r+")
  1103.  
  1104.                wordlist = pf.readlines()
  1105.                listlen = len(wordlist)
  1106.  
  1107.                tries = 0
  1108.  
  1109.                for lnpass in wordlist:
  1110.  
  1111.                   if b64sel.lower() == 'y':
  1112.                      lnpass = base64.b64decode(lnpass)
  1113.                   lnpass = lnpass.strip()
  1114.                   lnpass = lnpass.replace("\n","")
  1115.                   lnpass = str(lnpass)
  1116.                   loginok = checklogin(lnemail, lnpass, sslcon)
  1117.                   tries += 1
  1118.  
  1119.                   if 'OK' not in loginok and tries <= listlen:
  1120.                      #print('tried: %s') % str(lnpass)
  1121.                      print('login failure. trying next entry...')
  1122.                      if usecolor == 'color':
  1123.                         print('\033[33mtries: \033[35m' + str(tries) + '\033[33m out of \033[35m %s \033[0m' % str(listlen))
  1124.                      else:
  1125.                         print('tries: ' + str(tries) + ' out of ' + str(listlen))
  1126.  
  1127.                   else:
  1128.                      logging.info('INFO: LOGIN to %s successful!' % lnemail)
  1129.                      getimapmulti(lnemail, lnpass.strip(), sslcon)
  1130.                      tries = 100
  1131.                      break
  1132.  
  1133.                if tries > listlen and tries < 100:
  1134.                   print('exhausted all entries in password list.')
  1135.                   break
  1136.  
  1137.    # NOT USING PASSWORD LIST
  1138.    else:
  1139.  
  1140.       while efcount <= eflen:
  1141.          for line in ef.readlines():
  1142.  
  1143.             efcount += 1
  1144.  
  1145.             # WITH EMAIL AND PASSWORD IN SAME FILE
  1146.             if re.search(r'^[\,]$', line):
  1147.  
  1148.                line = line.strip()
  1149.                linevals = line.split(",")
  1150.  
  1151.                lnemail = linevals[0]
  1152.                lnemail = str(lnemail.strip())
  1153.                lnpass = linevals[1]
  1154.                lnpass = str(lnpass.strip())
  1155.                lnpass = lnpass.replace("\n","")
  1156.                if not filter(lambda x: x>'\x7f', lnpass):
  1157.                   lnpass = base64.b64decode(lnpass)
  1158.                print('using email address: ' + lnemail)
  1159.  
  1160.             else:
  1161.                lnemail = line.strip()
  1162.                print('using email address: ' + lnemail)
  1163.                lnpass = getpass.getpass('please enter password for above account --> ')
  1164.  
  1165.             loginok = checklogin(lnemail, lnpass, sslcon)
  1166.             print(loginok)
  1167.  
  1168.             while 'OK' not in loginok:
  1169.                lnpass = getpass.getpass('login failure. please check password and enter again --> ')
  1170.                loginok = checklogin(lnemail, lnpass, sslcon)
  1171.                print(loginok)
  1172.                if 'OK' in loginok:
  1173.                   break
  1174.                else:
  1175.                   print('login failure. trying next entry..')
  1176.                   continue
  1177.  
  1178.             logging.info('INFO: LOGIN to %s successful' % lnemail)
  1179.             getimapmulti(lnemail, lnpass, sslcon)
  1180.  
  1181.       if efcount > eflen:
  1182.          print("all emails and passwords have been processed.")
  1183.          sys.exit(0)
  1184.  
  1185. # SINGLE EMAIL ADDRESS
  1186. else:
  1187.  
  1188.    emailaddr = raw_input('please enter email address --> ')
  1189.  
  1190.    #VALIDATE EMAIL USING REGEX
  1191.    match = re.search(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,9})$', emailaddr)
  1192.  
  1193.    if match:
  1194.       if usecolor == 'color':
  1195.          print('\033[32m\nemail is valid\033[0m\n')
  1196.  
  1197.       else:
  1198.          print('email is valid\n')
  1199.  
  1200.    else:
  1201.       tries = 5
  1202.  
  1203.       while tries > 0:
  1204.  
  1205.          if usecolor == 'color':
  1206.             print('\033[31minvalid email format\033[0m\n')
  1207.             print('bad attempts: \033[33m' + str(6 - tries) + '\033[0m\n')
  1208.             print('\033[36myou have ' + str(tries) + ' attempts remaining.\033[0m\n')
  1209.  
  1210.          else:
  1211.             print('invalid email format')
  1212.             print('bad attempts: ' + str(6 - tries))
  1213.             print('you have ' + str(tries) + 'attempts remaining.')
  1214.  
  1215.          emailaddr = raw_input('please enter email again --> ')
  1216.  
  1217.          if match:
  1218.             tries = -1
  1219.             break
  1220.  
  1221.          else:
  1222.             tries = tries - 1
  1223.  
  1224.       if match:
  1225.          if usecolor == 'color':
  1226.             print('\n\033[32m email is valid \033[0m')
  1227.          else:
  1228.             print('email is valid')
  1229.  
  1230.       else:
  1231.          if usecolor == 'color':
  1232.             print('\033[31mERROR: unhandled exception. aborting..\033[0m\n')
  1233.          else:
  1234.             print('ERROR: unhandled exception. aborting..\n')
  1235.          logging.error('ERROR: unhandled exception. aborting program.')
  1236.          sys.exit()
  1237.  
  1238.       if tries is 0:
  1239.          if usecolor == 'color':
  1240.             print('\033[31m too many bad attempts using invalid format! \033[0m\n')
  1241.          else:
  1242.             print('too many bad attempts using invalid format!')
  1243.  
  1244.          logging.info('INFO: too many bad attempts using unproperly formatted email string. aborting program.')
  1245.          print('aborting..')
  1246.          sys.exit()
  1247.  
  1248.    if usewordlist.lower == 'y':
  1249.  
  1250.       pf = open(pwlistfile, "r")
  1251.       words = pf.readlines()
  1252.       total = len(words)
  1253.       count = 0
  1254.  
  1255.       while count <= total:
  1256.  
  1257.          for line in words():
  1258.  
  1259.             line = line.strip()
  1260.             line = line.replace("\n","")
  1261.             if b64sel.lower() == 'y':
  1262.                line = base64.b64decode(line)
  1263.             emailpass = line
  1264.             print("checking login authentication for %s" % emailaddr)
  1265.             logging.info('INFO: checking login authentication for %s' % emailaddr)
  1266.             loginok = checklogin(emailaddr, emailpass, sslcon)
  1267.             loginok = str(loginok)
  1268.             if usecolor == 'color':
  1269.                print("\033[31m result: \033[34m")
  1270.                print(loginok)
  1271.                print("\033[0m")
  1272.             else:
  1273.                print("result: %s") % loginok
  1274.  
  1275.             # INCREASE COUNTER BY 1
  1276.             count += 1
  1277.             print("tries: " + str(count) + " out of " + str(total))
  1278.  
  1279.             # WRONG PASSWORD
  1280.             if 'AUTHEN' in loginok:
  1281.                print("Wrong login credentials supplied for %s. Skipping to next password..." % emailaddr)
  1282.                logging.info('INFO: invalid password for %s. skipping to next password.' % emailaddr)
  1283.                continue
  1284.  
  1285.             # PASSWORD NOT CORRECTLY FORMATTED
  1286.             elif 'BAD' in loginok:
  1287.                emailpass = emailpass.strip()
  1288.                print("password format error. trying again..")
  1289.                loginok = checklogin(emailaddr, emailpass, sslcon)
  1290.                loginok = str(loginok)
  1291.                if 'OK' in loginok:
  1292.                   logging.info('INFO: LOGIN to %s successful' % emailaddr)
  1293.                   getimapmulti(emailaddr, emailpass, sslcon)
  1294.                   break
  1295.                continue
  1296.  
  1297.             else:
  1298.                logging.info('INFO: LOGIN to %s successful' % emailaddr)
  1299.                getimapmulti(emailaddr, emailpass, sslcon)
  1300.                break
  1301.  
  1302.    else:
  1303.  
  1304.       emailpass = getpass.getpass('please enter password --> ')
  1305.       getimap(emailaddr, emailpass, sslcon)
  1306.  
  1307. print("exiting program..")
  1308. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement