Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- ##################################################################################
- # 1)Configure the eMail adress
- # mail = EMail()
- # mail.confMail(eMail-address, password, smtp-server, smtp-port)
- # eg: mail.confMail('mail@mail.com', 'password', 'smtp.mail.com', 25)
- # 2)Create a new eMail
- # mail.newMail(subject)
- # eg: mail.newMail('Hello!')
- # 3)Add text and/or attachments
- # mail.addText(text)
- # addAttachment(path_to_file)
- # 4)Send eMail
- # mail.send(receiver)
- # eg: mail.send('mail@gmail.com') it can be sent multiple times to different adresses
- # mail.send() returns True if the eMail was sent successfully and False otherwise
- ##################################################################################
- import os, smtplib
- from email.MIMEMultipart import MIMEMultipart
- from email.MIMEText import MIMEText
- from email.mime.application import MIMEApplication
- class EMail(object):
- def __init__(self, ctimes=20):
- self.ctimes = ctimes
- self.connected = False
- def confMail(self, fr, psw, smtp, port):
- self.fr = fr
- self.psw = psw
- self.smtp = smtp
- self.port = port
- #Conexion
- tryMail = True
- tries = 0
- while tryMail:
- try:
- self.mailServer = mailServer = smtplib.SMTP(self.smtp, self.port)
- mailServer.ehlo()
- mailServer.starttls()
- mailServer.ehlo()
- acceptance = mailServer.login(self.fr, self.psw)
- if acceptance[0] == 235:
- tryMail = False
- self.connected = True
- else:
- tries += 1
- if tries >= self.ctimes:
- tryMail = False
- self.connected = False
- except:
- tries += 1
- if tries >= self.ctimes:
- tryMail = False
- self.connected = False
- def newMail(self, subject):
- self.msj = MIMEMultipart()
- self.msj['From'] = self.fr
- self.msj['Subject'] = subject
- def addText(self, text):
- self.msj.attach(MIMEText(text))
- def addAttachment(self, arch):
- part = MIMEApplication(open(arch,"rb").read())
- part.add_header('Content-Disposition', 'attachment', filename=arch.replace('\\', '/').split('/')[-1])
- self.msj.attach(part)
- def send(self, to):
- self.to = to
- self.msj['To'] = to
- #Enviar mensaje
- if self.connected:
- tryMail = True
- tries = 0
- while tryMail:
- try:
- # Enviar
- self.mailServer.sendmail(self.fr, self.to, self.msj.as_string())
- sent = True
- tryMail = False
- except:
- tries += 1
- if tries > self.ctimes:
- tryMail = False
- sent = False
- else:
- sent = False
- return sent
- def close(self):
- # Cerrar la conexion
- self.mailServer.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement