BufferingSMTPHandler.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright 2001-2002 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. #
  17. # This file is part of the Python logging distribution. See
  18. # http://www.red-dove.com/python_logging.html
  19. #
  20. """Test harness for the logging module. Tests BufferingSMTPHandler, an alternative implementation
  21. of SMTPHandler.
  22. Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
  23. """
  24. from email.mime.text import MIMEText
  25. import logging.handlers
  26. import smtplib
  27. class BufferingSMTPHandler(logging.handlers.BufferingHandler):
  28. def __init__(self, mailhost, fromaddr, toaddrs, subject, capacity):
  29. logging.handlers.BufferingHandler.__init__(self, capacity)
  30. self.mailhost = mailhost
  31. self.mailport = None
  32. self.fromaddr = fromaddr
  33. self.toaddrs = toaddrs
  34. self.subject = subject
  35. def flush(self):
  36. try:
  37. if len(self.buffer) > 0:
  38. port = self.mailport if self.mailport else smtplib.SMTP_PORT
  39. msg = "\n".join([self.format(record) for record in self.buffer])
  40. msg = MIMEText(msg.encode('utf-8'), _charset='utf-8')
  41. msg['Subject'] = self.subject
  42. msg['From'] = self.fromaddr
  43. msg['To'] = ",".join(self.toaddrs)
  44. smtp = smtplib.SMTP(self.mailhost, port)
  45. smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())
  46. smtp.quit()
  47. self.buffer = []
  48. except Exception as e:
  49. print(e)
  50. raise