Advertisement
Guest User

Untitled

a guest
Mar 15th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. from __future__ import print_function
  2. import logging
  3. import smtplib
  4. from email.mime.text import MIMEText
  5. from logging.handlers import BufferingHandler
  6.  
  7.  
  8. class BufferedSmtpHandler(BufferingHandler):
  9. """ This is a memoryhandler buffer, that never flush with big capacity (just to split MB emails)
  10. that will send a mail using configured smtp at the end
  11. """
  12.  
  13. def __init__(self, mailfrom, mailto, subject,
  14. smtp_username=None, smtp_password=None,
  15. smtp_host="localhost", smtp_port=None,
  16. send_mail=True, # usually the mail will be sent no matter what
  17. DEBUG=False, # in the DEBUG mode, no mail will be sent
  18. capacity=1024 * 10, ):
  19. super(BufferedSmtpHandler, self).__init__(capacity)
  20.  
  21. self.DEBUG = DEBUG
  22. self.mailfrom = mailfrom
  23. self.mailto = mailto
  24. self.subject = subject
  25. self.send_mail = send_mail
  26. self._default_send_mail = send_mail # the send_mail status after a flush
  27.  
  28. self.smtp_username = smtp_username
  29. self.smtp_password = smtp_password
  30. self.smtp_host = smtp_host
  31. self.smtp_port = int(smtp_port) if smtp_port else smtplib.SMTP_PORT
  32. self.setFormatter(logging.Formatter("%(message)s"))
  33.  
  34. def flush(self):
  35. if len(self.buffer) > 0:
  36. if self.send_mail:
  37. try:
  38. port = self.smtp_port
  39. recipients = self.mailto.split(",")
  40. print(("Sending mail" if not self.DEBUG else "Would send mail") +
  41. " to %s" % recipients)
  42. msg = MIMEText("\r\n".join(map(self.format, self.buffer)), _charset="utf-8")
  43. msg["From"] = self.mailfrom
  44. msg["To"] = recipients[0]
  45. msg["Subject"] = self.subject
  46.  
  47. if not self.DEBUG:
  48. smtp = smtplib.SMTP(self.smtp_host, port)
  49. if self.smtp_username and self.smtp_password:
  50. smtp.login(self.smtp_username, self.smtp_password)
  51. smtp.sendmail(self.mailfrom, recipients, msg.as_string())
  52. smtp.quit()
  53. else:
  54. print("in DEBUG no mail will be sent.")
  55. except Exception as e:
  56. print(e)
  57. raise e
  58. self.buffer = []
  59. self.send_mail = self._default_send_mail
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement