Foros del Web » Programando para Internet » Python »

libmail [Aporte]

Estas en el tema de libmail [Aporte] en el foro de Python en Foros del Web. libmail, es una clase que hice, para que el envio de emails, sea mas cómodo y fácil. Liberado bajo la siguiente licencia @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código ...
  #1 (permalink)  
Antiguo 30/07/2009, 14:02
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
libmail [Aporte]

libmail, es una clase que hice, para que el envio de emails, sea mas cómodo y fácil.

Liberado bajo la siguiente licencia
Código python:
Ver original
  1. #!/usr/bin/env python
  2. #coding: UTF-8
  3.  
  4. #This program is free software: you can redistribute it and/or modify
  5. #it under the terms of the GNU General Public License as published by
  6. #the Free Software Foundation, either version 3 of the License, or
  7. #(at your option) any later version.
  8.  
  9. #This program is distributed in the hope that it will be useful,
  10. #but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. #GNU General Public License for more details.
  13.  
  14. #You should have received a copy of the GNU General Public License
  15. #along with this program.  If not, see <http://www.gnu.org/licenses/>.
  16.  
  17. import smtplib
  18. from email.mime.text import MIMEText
  19. from email.mime.multipart import MIMEMultipart
  20. from email.mime.image import MIMEImage
  21. from email.mime.application import MIMEApplication
  22.  
  23. class Mail:
  24.     def __init__(self, host='localhost', user='', passwd='', name='', organization=''):
  25.         self.host = host
  26.         self.user = user
  27.         self.passwd = passwd
  28.         self.name = name
  29.         self.organization = organization
  30.         self.to_email = []
  31.         self.cc_email = []
  32.         self.bcc_email = []
  33.         self.mensaje = MIMEMultipart()
  34.         self.name = name
  35.         self.organization = organization
  36.         self.__set_headers()
  37.    
  38.     def __set_headers(self):
  39.         self.mensaje.add_header("Content-Disposition", "inline")
  40.         self.mensaje.add_header("Reply-To", "%s <%s>" % (self.name, self.user))
  41.         self.mensaje.add_header("Return-Path", "%s <%s>" % (self.name, self.user))
  42.         self.mensaje.add_header("From", "%s <%s>" % (self.name, self.user))
  43.         self.mensaje.add_header("Organization", "%s" % (self.organization))
  44.  
  45.     def set_subject(self, subject):
  46.         self.mensaje['Subject'] = subject
  47.  
  48.     def add_to(self, emails):
  49.         self.to_email.extend(emails)
  50.  
  51.     def add_cc(self, emails):
  52.         self.cc_email.extend(emails)
  53.  
  54.     def add_bcc(self, emails):
  55.         self.bcc_email.extend(emails)
  56.  
  57.     def clean_emails(self):
  58.         self.to_email = []
  59.         self.cc_email = []
  60.         self.bcc_email = []
  61.  
  62.     def get_message(self, filename, coding="utf8"):
  63.         try:
  64.             f = open(filename, "r")
  65.             body = f.read()
  66.         except IOError, e:
  67.             print e
  68.         else:
  69.             f.close()
  70.         body = unicode(body, coding)
  71.         body = body.encode(coding)
  72.         text = MIMEText(body, 'plain', coding)
  73.         self.mensaje.attach(text)
  74.  
  75.     def attach(self, filename, mimetype='application'):
  76.         try:
  77.             f = open(filename, "rb")
  78.             if mimetype == 'image':
  79.                 contenido = MIMEImage(f.read())
  80.             else:
  81.                 contenido = MIMEApplication(f.read())
  82.             contenido.add_header('Content-Disposition',
  83.                                  'attachment; filename = "%s"' % (filename.split('/')[-1]))
  84.             self.mensaje.attach(contenido)
  85.         except IOError, e:
  86.             print e
  87.         else:
  88.             f.close()
  89.    
  90.     def get_email_list(self):
  91.         email_list = []
  92.         if self.to_email:
  93.             email_list.extend(self.to_email)
  94.         else:
  95.             email_list.append('')
  96.         if self.cc_email:
  97.             email_list.extend(self.cc_email)
  98.         else:
  99.             email_list.append('')
  100.         email_list.extend(self.bcc_email)
  101.         return email_list
  102.  
  103.     def connect(self):
  104.         self.mailServer = smtplib.SMTP(self.host, 25)
  105.         self.mailServer.login(self.user, self.passwd)
  106.  
  107.     def send(self):
  108.         email_list = self.get_email_list()
  109.         result = self.mailServer.sendmail(self.user, email_list,
  110.                                      self.mensaje.as_string())
  111.         return result
  112.  
  113.     def quit(self):
  114.         self.mailServer.quit()

Ejemplo de uso:
Código python:
Ver original
  1. #!/usr/bin/env python
  2. #coding: UTF-8
  3.  
  4. import libmail
  5.  
  6. host = 'mail.midominio.com'
  7. passwd = 'password'
  8. name = 'Nombre del Usuario'
  9. organization = "Organizacion"
  10.  
  11. mail = libmail.Mail(host, user, passwd, name, organization)
  12. mail.set_subject('Asunto del correo')
  13. mail.attach('MSWord.doc')
  14. mail.attach('MSExcel.xls')
  15. mail.attach('Imagen.jpg', 'image')
  16. mail.get_message('mensaje.txt')
  17. mail.connect()
  18. mail.add_to("[email protected]".split(", ")) #Importante!, se envían listas como parámetros
  19. mail.add_cc("[email protected], [email protected]".split(", "))
  20. mail.add_bcc("[email protected], [email protected]".split(", "))
  21. mail.send()
  22. mail.quit()

Advertencia, esto no es para hacer spam!!!

Última edición por razpeitia; 31/07/2009 a las 16:05
  #2 (permalink)  
Antiguo 31/07/2009, 09:11
 
Fecha de Ingreso: octubre-2004
Ubicación: COLOMBIA
Mensajes: 240
Antigüedad: 19 años, 6 meses
Puntos: 3
Respuesta: libmail [Aporte]

Gracias, quedó genial, si me lo permites me gustaría colocarlo en mi blog.
__________________
Revista Código Latino
SoloCodigo
  #3 (permalink)  
Antiguo 31/07/2009, 15:43
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: libmail [Aporte]

Claro que si, de hecho lo liberare para la licencia GPL v3
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:51.