Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import email, getpass, imaplib, os, sys, sh
- import email.utils
- import time, datetime, re
- import glob, qrtools
- from twx.botapi import TelegramBot, ReplyKeyboardMarkup
- import netifaces as ni
- detach_dir = 'inbox' # directory where to save attachments (default: current)
- qrc_code = 'qrc'
- output_file = 'qrc_url.txt'
- #user = raw_input("Enter your GMail username:")
- #pwd = getpass.getpass("Enter your password: ")
- user = 'orion2@borma.biz'
- pwd = 'xxx'
- def generate_images():
- raw_qrc_files = glob.glob(qrc_code + "/*.*")
- qrc_files = [os.path.basename(f).split("-")[0] for f in raw_qrc_files if (len(f)-len(qrc_code)-1) < 33]
- files = glob.glob(detach_dir + "/*.pdf")
- files = [f for f in files if len(f)>26]
- for file in files :
- basename = os.path.basename(file)
- split = basename.split("=")[0]
- if split in qrc_files:
- continue
- print "processing "+ file
- cmd = sh.Command('/usr/bin/pdfimages')
- try:
- test = cmd("-p", file, qrc_code+'/'+ split)
- test.wait()
- except sh.ErrorReturnCode, e:
- print "ERROR " + file
- print e.stderr
- print fname
- print "pdf_err" + os.path.sep + basename
- #os.rename(fname, "pdf_err" + os.path.sep + basename)
- def get_max_count():
- files = glob.glob(detach_dir + "/*.pdf")
- files = [int(re.findall(r'inbox\/([\d]+)_', f)[0]) for f in files if re.match(r'inbox\/([\d]+)_', f)]
- if len(files) == 0:
- return 0;
- return max(files)
- try :
- ni.ifaddresses('eth0')
- ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'].replace("192.168.", "")
- except:
- ip = "NO.IP"
- #telegram bot init
- userId = -280211326
- bot = TelegramBot('102906697:AAHfi3FHbEKPVS6DLDA1Qf08GSdIzWtgAiQ')
- bot.update_bot_info().wait()
- bot.send_message(userId, "%s = %s" % (ip, __file__)).wait()
- # connecting to the gmail imap server
- m = imaplib.IMAP4_SSL("imap.gmail.com")
- m.login(user,pwd)
- m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead
- # use m.list() to get all the mailboxes
- 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)
- items = items[0].split() # getting the mails id
- max = get_max_count()
- #max = 380
- for emailid in items:
- #comment here
- #if int(emailid) >= 384:
- # break
- if int(emailid) <= max :
- print "skipping emailid : %s" % (emailid)
- continue
- resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
- email_body = data[0][1] # getting the mail content
- mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
- mail_content = "<content here>"
- for part in mail.walk():
- if part.get_content_type() == 'text/plain':
- mail_content = part.get_payload()
- mail_sender = mail["From"].split()[-1].replace("<", '').replace(">", "")
- if mail["Subject"] != None :
- print "["+mail["From"]+"] :" + mail["Subject"]
- else :
- print "["+mail["From"]+"] :"
- tglstr = email.utils.parsedate(mail['date'])
- tick = time.mktime(tglstr)
- tgl = datetime.datetime.fromtimestamp(tick)
- # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
- if mail["Subject"] != None :
- fname = '%05d_000_%s=%s=%s.htm' % (int(emailid), tgl.strftime('%Y%m%d'), mail_sender, mail["Subject"].replace(" ", "_").replace("/", "_"))
- else :
- fname = '%05d_000_%s=%s.htm' % (int(emailid), tgl.strftime('%Y%m%d'), mail_sender)
- if len(fname) > 253:
- fname = fname[0:253]
- fname_path = os.path.join(detach_dir, fname)
- with open(fname_path, "w") as f:
- f.write(mail_content)
- #Check if any attachments at all
- if mail.get_content_maintype() != 'multipart':
- continue
- counter = 1
- for part in mail.walk():
- # multipart are just containers, so we skip them
- if part.get_content_maintype() == 'multipart':
- continue
- # is this part an attachment ?
- if part.get('Content-Disposition') is None:
- continue
- orifilename = part.get_filename()
- # if there is no filename, we create one with a counter to avoid duplicates
- if not orifilename:
- orifilename = '%05d_%03d%s' % (int(emailid), counter, 'bin')
- counter += 1
- filename = '%05d_%03d_%s=%s' % (int(emailid), counter, tgl.strftime('%Y%m%d'), orifilename)
- counter += 1
- att_path = os.path.join(detach_dir, filename)
- #Check if its already there
- if not os.path.isfile(att_path) :
- # finally write the stuff
- fp = open(att_path, 'wb')
- fp.write(part.get_payload(decode=True))
- fp.close()
- generate_images()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement