Advertisement
juliozaco

email_traps_disfar.py

Jun 21st, 2011
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.22 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name:        email_traps_disfar
  3. # Purpose:
  4. #
  5. # Author:      julio
  6. #
  7. # Created:     16/06/2011
  8. # Copyright:   (c) julio 2011
  9. # Licence:     <your licence>
  10. #-------------------------------------------------------------------------------
  11. #!/usr/bin/env python
  12. #-------------------------------------------------------------------------------
  13. # - recorremos todos los ficheros de la carpeta de errores puesta en parametros generales
  14. #           parametros envio de correo
  15. #
  16. # - en folder poner la carpeta donde se guardan los ficheros de error
  17. #       o dejarlo en blanco si el script está en la misma
  18. #
  19. # - necesita un fichero texto smtp.txt con primera linea servidor salida SMTP y segunda la contraseña
  20. #
  21. # - confeccionamos email a nuestro gusto y enviamos
  22. #
  23. # - renombramos fichero de error a TRATADO_<filename> para no volverlo a tratar
  24. #
  25. # - existe un fichero de errores para consultas
  26. #
  27. #-------------------------------------------------------------------------------
  28.  
  29. import smtplib, os, re, datetime, shutil
  30. import xml.dom.minidom
  31.  
  32. from email.Parser import Parser
  33. from email.mime.text import MIMEText
  34. from email.mime.image import MIMEImage
  35. from email.mime.multipart import MIMEMultipart
  36. from email.MIMEBase import MIMEBase
  37. from email import Encoders
  38.  
  39. class XML_Trap(object):
  40.     def __init__(self):
  41.         self.origen = ''
  42.         self.destino =[]
  43.         self.asunto = ''
  44.         self.fecha = ''
  45.         self.hora = ''
  46.         self.error = ''
  47.         self.valores = ''
  48.  
  49.     def limpia(self, filename):
  50.         # ccs mete tabuladores y saltos de linea que molestan a la hora de tratar xml
  51.         self.filename= filename
  52.         fic_xml = open(filename,'r')
  53.         self.xmldata = fic_xml.read()
  54.         fic_xml.close()
  55.         self.xmldata = self.xmldata.replace('\t','')
  56.         self.xmldata = self.xmldata.replace('\n','')
  57.  
  58.     def recoge(self):
  59.         try:
  60.             xmlerror = xml.dom.minidom.parseString(self.xmldata)
  61.             for n in xmlerror.getElementsByTagName("destino"):
  62.                 self.destino.append(str(n.firstChild.data))
  63.             self.origen = xmlerror.getElementsByTagName("origen")[0].firstChild.data
  64.             self.asunto = xmlerror.getElementsByTagName("asunto")[0].firstChild.data
  65.             self.fecha = xmlerror.getElementsByTagName("fecha")[0].firstChild.data
  66.             self.hora = xmlerror.getElementsByTagName("hora")[0].firstChild.data
  67.             self.error = xmlerror.getElementsByTagName("error")[0].firstChild.data
  68.             try:
  69.                 self.valores = xmlerror.getElementsByTagName("valores")[0].firstChild.data
  70.             except Exception:
  71.                 pass
  72.  
  73.         except Exception, error:
  74.             print error
  75.             fic_algofuemal = open('email_traps_disfar_error.txt','a')
  76.             fic_algofuemal.write(str(datetime.datetime.now()) + ' ' + self.filename + 'Error: ' + str(error) + '\n')
  77.             fic_algofuemal.close()
  78.  
  79.  
  80. def busca_encarpeta():
  81.     for (path, dirs, files) in os.walk(folder):
  82.       for file in files:
  83.         filename = os.path.join(path, file)
  84.         if re.match('ERROR\d{0,12}_\d{1,3}.XML',filename):
  85.             #print filename
  86.             xml1.limpia(filename)
  87.             xml1.recoge()
  88.             if xml1.asunto<>'':
  89.                 email_listo()
  90.  
  91. def email_listo():
  92.     # organizamos a nuestro antojo la composición del email
  93.     # pero hay que poner fijo datos del servidor smtp de cada uno
  94.     usuario_smtp = str(xml1.origen)
  95.     para_email = xml1.destino
  96.     asunto_email = str(xml1.asunto + '_' + xml1.fecha + '_'+ xml1.hora)
  97.     texto_email = 'Error: '+ str(xml1.error) + '\nValores: '+ str(xml1.valores)
  98.     adjunto_email = str(xml1.filename)
  99.     # si existe fichero datos smtp los cogemos
  100.     if os.path.exists('smtp.txt'):
  101.         fic_smtp = open('smtp.txt','r')
  102.         smtp_datos = fic_smtp.readlines()
  103.         fic_smtp.close()
  104.         servidor_smtp = smtp_datos[0][:-1]
  105.         contra_smtp = smtp_datos[1][:-1]
  106.  
  107.     #
  108.     mandaemail(usuario_smtp, contra_smtp, servidor_smtp, para_email, asunto_email, texto_email, adjunto_email)
  109.     # renombramos para no volver a tratar
  110.     shutil.copy2(xml1.filename, 'TRATADO_'+ xml1.filename)
  111.     os.remove(xml1.filename)
  112.  
  113.  
  114. def mandaemail(user,passw,smtp,aquien,subject,texto,adjunto):
  115.     msg = MIMEMultipart()
  116.  
  117.     textomsg=MIMEText(texto)
  118.     msg['Subject']=subject
  119.     msg['From']=user
  120.     msg['To']=', '.join(aquien)
  121.     msg.attach(textomsg)
  122.  
  123.     if adjunto<>"":
  124.         part = MIMEBase('application', "octet-stream")
  125.         part.set_payload( open(adjunto,"rb").read() )
  126.         Encoders.encode_base64(part)
  127.         (directorio, fichero) = os.path.split(adjunto)
  128.         part.add_header('Content-Disposition', 'attachment; filename="%s"'
  129.                             % fichero)
  130.         msg.attach(part)
  131.  
  132.     smtp=smtplib.SMTP(smtp)
  133.     smtp.login(user,passw)
  134.  
  135.     smtp.sendmail(msg['From'], aquien, msg.as_string())
  136.     smtp.close()
  137.  
  138.  
  139. folder = ''
  140. contra_smtp = 'la contraseña de vuestro cuenta de email SMTP'
  141. servidor_smtp = 'vuestro servidor de correo de salida SMTP'
  142.  
  143. xml1 = XML_Trap()
  144. if __name__ == '__main__':
  145.     busca_encarpeta()
  146.  
  147. exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement