Advertisement
Guest User

Untitled

a guest
Feb 20th, 2018
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.65 KB | None | 0 0
  1. import email, getpass, imaplib, os, sys, sh
  2.  
  3. import email.utils
  4. import time, datetime, re
  5. import glob, qrtools
  6.  
  7. from twx.botapi import TelegramBot, ReplyKeyboardMarkup
  8.  
  9. import netifaces as ni
  10.  
  11.  
  12. detach_dir = 'inbox' # directory where to save attachments (default: current)
  13. qrc_code = 'qrc'
  14. output_file = 'qrc_url.txt'
  15. #user = raw_input("Enter your GMail username:")
  16. #pwd = getpass.getpass("Enter your password: ")
  17.  
  18. user = 'orion2@borma.biz'
  19. pwd = 'xxx'
  20.  
  21. def generate_images():
  22.  
  23.     raw_qrc_files = glob.glob(qrc_code + "/*.*")
  24.     qrc_files = [os.path.basename(f).split("-")[0] for f in raw_qrc_files if (len(f)-len(qrc_code)-1) < 33]
  25.  
  26.     files = glob.glob(detach_dir + "/*.pdf")
  27.     files =  [f for f in files if len(f)>26]
  28.     for file in files :
  29.         basename = os.path.basename(file)
  30.         split = basename.split("=")[0]
  31.  
  32.         if split in qrc_files:
  33.             continue
  34.  
  35.         print "processing  "+ file
  36.  
  37.         cmd =  sh.Command('/usr/bin/pdfimages')
  38.         try:
  39.             test = cmd("-p", file, qrc_code+'/'+ split)
  40.             test.wait()
  41.         except sh.ErrorReturnCode, e:
  42.             print "ERROR " + file
  43.             print e.stderr
  44.             print fname
  45.             print "pdf_err" + os.path.sep + basename
  46.             #os.rename(fname, "pdf_err" + os.path.sep + basename)
  47.  
  48. def get_max_count():
  49.     files = glob.glob(detach_dir + "/*.pdf")
  50.     files = [int(re.findall(r'inbox\/([\d]+)_', f)[0]) for f in files if re.match(r'inbox\/([\d]+)_', f)]
  51.     if len(files) == 0:
  52.         return 0;
  53.  
  54.     return max(files)
  55.  
  56. try :
  57.     ni.ifaddresses('eth0')
  58.     ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'].replace("192.168.", "")
  59. except:
  60.     ip = "NO.IP"
  61.  
  62. #telegram bot init
  63. userId = -280211326
  64. bot = TelegramBot('102906697:AAHfi3FHbEKPVS6DLDA1Qf08GSdIzWtgAiQ')
  65. bot.update_bot_info().wait()
  66. bot.send_message(userId, "%s = %s" % (ip, __file__)).wait()
  67.  
  68.  
  69. # connecting to the gmail imap server
  70. m = imaplib.IMAP4_SSL("imap.gmail.com")
  71. m.login(user,pwd)
  72. m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead
  73. # use m.list() to get all the mailboxes
  74.  
  75. resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
  76. items = items[0].split() # getting the mails id
  77.  
  78. max = get_max_count()
  79. #max = 380
  80.  
  81. for emailid in items:
  82.  
  83.     #comment here
  84.     #if int(emailid) >= 384:
  85.     #   break
  86.  
  87.     if int(emailid) <= max :
  88.         print "skipping emailid : %s" % (emailid)
  89.         continue
  90.  
  91.     resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
  92.     email_body = data[0][1] # getting the mail content
  93.     mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
  94.  
  95.     mail_content = "<content here>"
  96.     for part in mail.walk():
  97.         if part.get_content_type() == 'text/plain':
  98.             mail_content = part.get_payload()
  99.  
  100.     mail_sender = mail["From"].split()[-1].replace("<", '').replace(">", "")
  101.  
  102.     if mail["Subject"] != None :
  103.         print "["+mail["From"]+"] :" + mail["Subject"]
  104.     else :
  105.         print "["+mail["From"]+"] :"
  106.  
  107.     tglstr = email.utils.parsedate(mail['date'])
  108.     tick = time.mktime(tglstr)
  109.     tgl = datetime.datetime.fromtimestamp(tick)
  110.     # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
  111.  
  112.     if mail["Subject"] != None :
  113.         fname = '%05d_000_%s=%s=%s.htm' % (int(emailid), tgl.strftime('%Y%m%d'), mail_sender, mail["Subject"].replace(" ", "_").replace("/", "_"))
  114.     else :
  115.         fname = '%05d_000_%s=%s.htm' % (int(emailid), tgl.strftime('%Y%m%d'), mail_sender)
  116.     if len(fname) > 253:
  117.         fname = fname[0:253]
  118.  
  119.     fname_path = os.path.join(detach_dir, fname)
  120.     with open(fname_path, "w") as f:
  121.         f.write(mail_content)
  122.  
  123.     #Check if any attachments at all
  124.     if mail.get_content_maintype() != 'multipart':
  125.         continue
  126.  
  127.     counter = 1
  128.     for part in mail.walk():
  129.         # multipart are just containers, so we skip them
  130.         if part.get_content_maintype() == 'multipart':
  131.             continue
  132.  
  133.         # is this part an attachment ?
  134.         if part.get('Content-Disposition') is None:
  135.             continue
  136.  
  137.         orifilename = part.get_filename()
  138.  
  139.         # if there is no filename, we create one with a counter to avoid duplicates
  140.         if not orifilename:
  141.             orifilename = '%05d_%03d%s' % (int(emailid), counter, 'bin')
  142.             counter += 1
  143.  
  144.         filename = '%05d_%03d_%s=%s' % (int(emailid), counter, tgl.strftime('%Y%m%d'), orifilename)
  145.         counter += 1
  146.  
  147.         att_path = os.path.join(detach_dir, filename)
  148.  
  149.         #Check if its already there
  150.         if not os.path.isfile(att_path) :
  151.             # finally write the stuff
  152.             fp = open(att_path, 'wb')
  153.             fp.write(part.get_payload(decode=True))
  154.             fp.close()
  155.  
  156. generate_images()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement