Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as Python by ajuma ( 15 years ago )
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       untitled.py
#       
#       Copyright 2010 adnan <adnan@Avarda-Kedavra>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but 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.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#           Developed by Adnany J. Salim


import zipfile
import smtplib
import shutil
import zlib
import time
import sys
import os
import re

from email.MIMEMultipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders

smtp = smtplib.SMTP('tz-ohi-exc-01.tanzania.africa.barclays.org')
source_directory = "y:\ut\reports"
ext = '@tanzania.bafrica.barclays.com'

#contacts dictionary (contacts + respective reports names)
date    = time.asctime(time.localtime(time.time()))
day_int = int(date[8:10]) - 1
day_s     = str(day_int)

days = {'1' : '01','2' : '02','3' : '03','4' : '04','5' : '05','6' : '06','7' : '07','8' : '08','9' : '09'} 

for item in days:
 if day_s == item:
  day = days[item]
  
Recepients = {
    (r'bsysu006.' + day , 'Statutory Minimum Reserve Liquidity Report') : ['bupe.mwakabaga'+ext,'gilbert.sifaeli'+ext],
    (r'bsysu018.' + day , 'Account Without Signatures Report')    : ['salome.masenga'+ext,'Tanzania.IT-Helpdesk'+ext],
    (r'bsysu045.' + day , 'Underdrawn Limits Balance Report')   : ['Tanzania.IT-Helpdesk'+ext],
    (r'bsysu046.' + day , 'Balances per Account Type Report')   : ['bupe.mwakabaga'+ext,'gilbert.sifaeli'+ext],
    (r'b...a050.'  + day , 'Revaluation Report')       : ['salome.masenga'+ext,'Tanzania.IT-Helpdesk'+ext],
    (r'b...a009.'  + day , 'Transaction Journal')       : ['adnany.juma'+ext,'Tanzania.IT-Helpdesk'+ext],
 (r'bsysun08.' + day , 'Forex Open Position - Transiaction Journal Report') : ['adnany.juma'+ext,'Tanzania.IT-Helpdesk'+ext],
    (r'sms'      , 'SMSACQTL Settlement, SMSACQTL Transaction & Incoming Chargeback Reports') : ['adnany.juma'+ext,'Tanzania.IT-Helpdesk'+ext],
    (r'bsysu645.'+ day , 'Daily List of Newly Opened Barclays Loans & Staff Loans') : ['adnany.juma'+ext,'Tanzania.IT-Helpdesk'+ext]
    }

Months = { 'Jan' : '01','Feb' : '02','Mar' : '03','Apr' : '04','May' : '05','Jun' : '06','Jul' : '07','Aug' : '08','Sep' : '09','Oct' : '10','Nov' : '11','Dec' : '12'}

FROM = 'adnany.juma'+ext
NotFound = []
Found  = {}


def SendMailWithAttachment(recepients,subject,PathToAttachment):

    # attach the zip file
    mssg = MIMEMultipart()
    mssg['Subject'] = subject

    #the body part of the email
    html = """
        <html>
          <head></head>
              <body>
                <p>Morning Team,<br>
                How are you?<br>
                Please receive the """ + subject +  """ report for today!<br>
                This is a test massage, when you get it inform Adnany and <b>delete it</b>!!
                </p>
              </body>
        </html>
            """
    part1 = MIMEText(html, 'html')
    mssg.attach(part1)

    # pin the attachment with email
    part = MIMEBase('application',"octet-stream")
    part.set_payload(open(PathToAttachment,"rb").read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' %
    os.path.basename(PathToAttachment))
    mssg.attach(part)

    # send the email with attachment
    #smtp = smtplib.SMTP('tz-ohi-exc-01.tanzania.africa.barclays.org')
    smtp.sendmail(FROM, recepients, mssg.as_string())
    #smtp.quit()

#Search function    
def SearchFile&#40;pattern,string&#41;:
    match = re.search(pattern,string)
    if match:
        return True
    else:
        return False

def Zip_me_up(ex_code,ex_name,recepient_list):
    ZipPath = "y:\ut\reports\Zipped\" + ex_code + ".zip"
    new_zip = zipfile.ZipFile&#40;ZipPath,'a',zipfile.ZIP_DEFLATED&#41;
    status = 0

    #search for report in the source directory
    for filename in os.listdir(source_directory):
        if SearchFile&#40;ex_code,filename&#41;:
            new_zip.write(os.path.join(source_directory,filename),filename)
            status = 1  
    new_zip.close()
    if status: 
  print 'Sending ' + ex_code + '..'
  SendMailWithAttachment(recepient_list,ex_name,ZipPath)
    else:
            NotFound.append(ex_code) # populate the list of not found reports
            
# Backup of reports
def BackUp():
 print "Running today's Backup routine... n"
 
 date = time.localtime(time.time())
 date_m = time.asctime(date)
 date_year = date_m[4:7] + '-' + date_m[-4:] # name of month folder
 
 for month in Months:
  if month == date_m[4:7]:
   this_month = Months[month]

 report_name = date_m[8:10] + this_month + date_m[-2:] + '.zip'
 
 date_m = str(date[2]) + str(date[1]) + str(date[0])

 backup_folder = 'y:\ut\reports\'
 todays_report = 'y:\ut\reports\backup\reports.' + report_name
 YearFolder = str(date[0]) # name of year folder
 
 CheckYearFolder = os.path.isdir(backup_folder + YearFolder)
 CheckMonthFolder = os.path.isdir(backup_folder + YearFolder + '\' + date_year)
  
 if CheckYearFolder:   
  if CheckMonthFolder:
   print "Copying today's reports into " + date_year + " backup folder.."
   shutil.copy(todays_report , backup_folder + YearFolder + '\' + date_year)
   print "Successful copied today's reports!n"
 
  else:
   print 'Making ' + date_year + ' backup folder ..'
   os.mkdir(backup_folder + YearFolder + '\' + date_year)
   print "Copying today's reports into " + date_year + " backup folder..."
   shutil.copy(todays_report , backup_folder + YearFolder + '\' + date_year)
   print "Successful copied today's reports!n"
 else:
  print 'Making ' + YearFolder + ' backup folder ..'
  os.mkdir(backup_folder + YearFolder)
  
  print 'Making ' + date_year + ' backup folder ..'
  os.mkdir(backup_folder + YearFolder + '\' + date_year)
  print "Copying today's reports into " + date_year + " backup folder..."
  shutil.copy(todays_report , backup_folder + YearFolder + '\'+ date_year)
  print "Successful copied today's reports!"

# report analysis processing
def analysis_reports():
 import time
 
 date_m = time.asctime(time.localtime(time.time()))
 date_modified = date_m[4:11] + ', ' + date_m[-4:]
 path_to_file = 'y:\ut\reports\' + date_modified + '.txt' # path to where the report analysis file will be created
 
 file_object = file&#40;path_to_file, 'w'&#41;
 
 width = 72  # width of the formatted file
 status_width = 21
 time_width = 21
 item_width = 30

 header_format = '%-*s%*s%*s'
 format        = '%-*s%*.2f'
 main_header   = '%-*s%*s%*s%*s%*s%*s%*s'
 
 print >> file_object, 'n'
 print >> file_object, main_header % ( 9, 'Extracts', 7 , 'Delivery', 9 , 'Analysis' , 7 , 'Report' , 3 ,'--', 5, '(EDAR)', 30, date_m)
 print >> file_object, '1. Extracts found and Sent'
 print >> file_object, '=' * width
 print >> file_object, header_format % (item_width, 'Extract Name', time_width , 'Time Sent', status_width, 'Status')
 print >> file_object, '-' * width

 print >> file_object, 'n'
 for name,time in Found.iteritems():
  print >> file_object, header_format % (item_width, name , time_width , time , status_width, 'Sent')
   
 print >> file_object, 'n'

 print >> file_object, '2. Extracts not found'
 print >> file_object, '=' * width
 print >> file_object, header_format % (item_width, 'Extract Name', time_width , 'Time Sent', status_width, 'Status')
 print >> file_object, '-' * width
 
 print >> file_object, 'n'
 for name in NotFound:
  print >> file_object, header_format % (item_width, name , time_width , 'N/A' , status_width, 'Not Found')

 print >> file_object, 'n'

 print >> file_object, 'Sent by  : ' + '_' * 20
 print >> file_object, 'n'
 print >> file_object, 'Signature: ' + '_' * 20 
 
 file_object.close()
 
 return date_modified,path_to_file
 
            
def main():
  
 BackUp() # call the backup function
 print 'n' 
 zipped = 'y:\ut\reports\Zipped' # folder where all the zipped files will be put
 if os.path.isdir(zipped):
  deleteMe = os.listdir(zipped)
  print 'Clearing the compressed files folder..'
  for deleted in deleteMe: 
   print 'Deleting ' + deleted
   remove_file = os.path.join(zipped, deleted)
   os.unlink&#40;remove_file&#41;
 else:
  print 'Making folder to store compressed files ..'
  os.mkdir(zipped)
 print 'n'  
 
 print 'Running report sending module..'
 for extract,recepient in Recepients.iteritems():
  Zip_me_up(extract[0],extract[1],recepient)
  if extract[0] in NotFound:
   print 't' + extract[0] + ' not found..'
  else:
   date_m = time.asctime(time.localtime(time.time()))
   Found[extract[0]] =  date_m # populate the dictionery of found reports 
                
    # Preparing the report for ITHD       
 analysis_name = analysis_reports() # call the report analysis function
        
 # Compressing the MRA report and Sending
 path = 'y:\ut\reports\' + analysis_name[0] + '.zip'
 new_zip = zipfile.ZipFile&#40;path,'a',zipfile.ZIP_DEFLATED&#41;
 new_zip.write(analysis_name[1])
 new_zip.close()
 SendMailWithAttachment('Tanzania.IT-Helpdesk'+ext,'Missing Report',path)
 
 smtp.quit()
 
 return 0

if __name__ == '__main__':
 main()

 

Revise this Paste

Your Name: Code Language: