BufferingSMTPHandler.py 2.2 KB

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