Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #-------------------------------------------------------------------------------
- # Name: email_traps_disfar
- # Purpose:
- #
- # Author: julio
- #
- # Created: 16/06/2011
- # Copyright: (c) julio 2011
- # Licence: <your licence>
- #-------------------------------------------------------------------------------
- #!/usr/bin/env python
- #-------------------------------------------------------------------------------
- # - recorremos todos los ficheros de la carpeta de errores puesta en parametros generales
- # parametros envio de correo
- #
- # - en folder poner la carpeta donde se guardan los ficheros de error
- # o dejarlo en blanco si el script está en la misma
- #
- # - necesita un fichero texto smtp.txt con primera linea servidor salida SMTP y segunda la contraseña
- #
- # - confeccionamos email a nuestro gusto y enviamos
- #
- # - renombramos fichero de error a TRATADO_<filename> para no volverlo a tratar
- #
- # - existe un fichero de errores para consultas
- #
- #-------------------------------------------------------------------------------
- import smtplib, os, re, datetime, shutil
- import xml.dom.minidom
- from email.Parser import Parser
- from email.mime.text import MIMEText
- from email.mime.image import MIMEImage
- from email.mime.multipart import MIMEMultipart
- from email.MIMEBase import MIMEBase
- from email import Encoders
- class XML_Trap(object):
- def __init__(self):
- self.origen = ''
- self.destino =[]
- self.asunto = ''
- self.fecha = ''
- self.hora = ''
- self.error = ''
- self.valores = ''
- def limpia(self, filename):
- # ccs mete tabuladores y saltos de linea que molestan a la hora de tratar xml
- self.filename= filename
- fic_xml = open(filename,'r')
- self.xmldata = fic_xml.read()
- fic_xml.close()
- self.xmldata = self.xmldata.replace('\t','')
- self.xmldata = self.xmldata.replace('\n','')
- def recoge(self):
- try:
- xmlerror = xml.dom.minidom.parseString(self.xmldata)
- for n in xmlerror.getElementsByTagName("destino"):
- self.destino.append(str(n.firstChild.data))
- self.origen = xmlerror.getElementsByTagName("origen")[0].firstChild.data
- self.asunto = xmlerror.getElementsByTagName("asunto")[0].firstChild.data
- self.fecha = xmlerror.getElementsByTagName("fecha")[0].firstChild.data
- self.hora = xmlerror.getElementsByTagName("hora")[0].firstChild.data
- self.error = xmlerror.getElementsByTagName("error")[0].firstChild.data
- try:
- self.valores = xmlerror.getElementsByTagName("valores")[0].firstChild.data
- except Exception:
- pass
- except Exception, error:
- print error
- fic_algofuemal = open('email_traps_disfar_error.txt','a')
- fic_algofuemal.write(str(datetime.datetime.now()) + ' ' + self.filename + 'Error: ' + str(error) + '\n')
- fic_algofuemal.close()
- def busca_encarpeta():
- for (path, dirs, files) in os.walk(folder):
- for file in files:
- filename = os.path.join(path, file)
- if re.match('ERROR\d{0,12}_\d{1,3}.XML',filename):
- #print filename
- xml1.limpia(filename)
- xml1.recoge()
- if xml1.asunto<>'':
- email_listo()
- def email_listo():
- # organizamos a nuestro antojo la composición del email
- # pero hay que poner fijo datos del servidor smtp de cada uno
- usuario_smtp = str(xml1.origen)
- para_email = xml1.destino
- asunto_email = str(xml1.asunto + '_' + xml1.fecha + '_'+ xml1.hora)
- texto_email = 'Error: '+ str(xml1.error) + '\nValores: '+ str(xml1.valores)
- adjunto_email = str(xml1.filename)
- # si existe fichero datos smtp los cogemos
- if os.path.exists('smtp.txt'):
- fic_smtp = open('smtp.txt','r')
- smtp_datos = fic_smtp.readlines()
- fic_smtp.close()
- servidor_smtp = smtp_datos[0][:-1]
- contra_smtp = smtp_datos[1][:-1]
- #
- mandaemail(usuario_smtp, contra_smtp, servidor_smtp, para_email, asunto_email, texto_email, adjunto_email)
- # renombramos para no volver a tratar
- shutil.copy2(xml1.filename, 'TRATADO_'+ xml1.filename)
- os.remove(xml1.filename)
- def mandaemail(user,passw,smtp,aquien,subject,texto,adjunto):
- msg = MIMEMultipart()
- textomsg=MIMEText(texto)
- msg['Subject']=subject
- msg['From']=user
- msg['To']=', '.join(aquien)
- msg.attach(textomsg)
- if adjunto<>"":
- part = MIMEBase('application', "octet-stream")
- part.set_payload( open(adjunto,"rb").read() )
- Encoders.encode_base64(part)
- (directorio, fichero) = os.path.split(adjunto)
- part.add_header('Content-Disposition', 'attachment; filename="%s"'
- % fichero)
- msg.attach(part)
- smtp=smtplib.SMTP(smtp)
- smtp.login(user,passw)
- smtp.sendmail(msg['From'], aquien, msg.as_string())
- smtp.close()
- folder = ''
- contra_smtp = 'la contraseña de vuestro cuenta de email SMTP'
- servidor_smtp = 'vuestro servidor de correo de salida SMTP'
- xml1 = XML_Trap()
- if __name__ == '__main__':
- busca_encarpeta()
- exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement