Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class BufferSMTPHandler(handlers.BufferingHandler):
'''SMTPHandler that send one email per flush'''
def __init__(self, email, paths):
handlers.BufferingHandler.__init__(self, capacity=5)
self.state = get_state(path)
self.buffer = self.state.buffer
self.email = email
smtp_formatter = logging.Formatter("%(asctime)s %(message)s",
datefmt='%Y-%m-%d %H:%M')
self.setFormatter(smtp_formatter)
def flush(self):
'''Flush if we exceed threshold; otherwise save the buffer'''
if not self.buffer:
self.outcome = Outcome(None, 'Buffer was empty')
return
if len(self.buffer) < self.capacity:
self.outcome = Outcome(None, 'Buffer no sufficiently full')
self.save()
return
body = str()
for record in self.buffer:
body = body + self.format(record) + "\r\n"
msg = MIMEText(body.encode('utf-8'), _charset="utf-8")
msg['From'] = self.email['fromaddr']
msg['To'] = self.email['toaddr']
msg['Subject'] = Header("POCA log")
if self.email['starttls']:
try:
smtp = smtplib.SMTP(self.email['host'], 587, timeout=10)
ehlo = smtp.ehlo()
except (ConnectionRefusedError, socket.gaierror, socket.timeout) \
as error:
self.outcome = Outcome(False, str(error))
self.save()
return
smtp.starttls()
try:
smtp.login(self.email['fromaddr'], self.email['password'])
except smtplib.SMTPAuthenticationError as error:
self.outcome = Outcome(False, str(error))
self.save()
return
else:
try:
smtp = smtplib.SMTP(self.email['host'], 25, timeout=10)
ehlo = smtp.ehlo()
except (ConnectionRefusedError, socket.gaierror, socket.timeout) \
as error:
self.outcome = Outcome(False, str(error))
self.save()
return
try:
smtp.sendmail(self.email['fromaddr'], [self.email['toaddr']],
msg.as_string())
self.outcome = Outcome(True, "Succesfully sent email")
except (smtplib.SMTPException, socket.timeout) as error:
self.outcome = Outcome(False, str(error))
self.save()
return
smtp.quit()
self.buffer = []
self.save()
def save(self):
'''Save the buffer for some other time (it either isn't full yet or we
can't empty it)'''
self.state.buffer = self.buffer
self.state.save()
self.buffer = []
def shouldFlush(self, record):
'''Returns false to stop automatic flushing (we flush on close)'''
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment