Guest User

Untitled

a guest
Jun 14th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.70 KB | None | 0 0
  1. from email.mime.text import MIMEText
  2. from email.mime.image import MIMEImage
  3. from email.mime.multipart import MIMEMultipart
  4. # from email.Utils import formatdate
  5. from logging.handlers import SMTPHandler
  6. import logging
  7. import os.path
  8. import smtplib
  9.  
  10. from email.utils import formatdate
  11.  
  12. from past.types import basestring
  13.  
  14.  
  15. class SMTPHandlerWithAttachment(SMTPHandler):
  16. """
  17. A handler class which sends an SMTP email for each logging event.
  18. """
  19.  
  20. def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, attachment=None):
  21. """
  22. Initialize the handler.
  23. Initialize the instance with the from and to addresses and subject
  24. line of the email. To specify a non-standard SMTP port, use the
  25. (host, port) tuple format for the mailhost argument. To specify
  26. authentication credentials, supply a (username, password) tuple
  27. for the credentials argument. To specify the use of a secure
  28. protocol (TLS), pass in a tuple for the secure argument. This will
  29. only be used when authentication credentials are supplied. The tuple
  30. will be either an empty tuple, or a single-value tuple with the name
  31. of a keyfile, or a 2-value tuple with the names of the keyfile and
  32. certificate file. (This tuple is passed to the `starttls` method).
  33. """
  34. logging.Handler.__init__(self)
  35. if isinstance(mailhost, tuple):
  36. self.mailhost, self.mailport = mailhost
  37. else:
  38. self.mailhost, self.mailport = mailhost, None
  39. if isinstance(credentials, tuple):
  40. self.username, self.password = credentials
  41. else:
  42. self.username = None
  43. self.fromaddr = fromaddr
  44. if isinstance(toaddrs, basestring):
  45. toaddrs = [toaddrs]
  46. self.toaddrs = toaddrs
  47. self.subject = subject
  48. self.secure = secure
  49. self._timeout = 5.0
  50. self.attachment = attachment
  51.  
  52. def emit(self, record):
  53. """
  54. Emit a record.
  55. Format the record and send it to the specified addressees.
  56. """
  57. try:
  58. port = self.mailport
  59. if not port:
  60. port = smtplib.SMTP_PORT
  61. smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)
  62. # msg = self.format(record)
  63. # msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
  64. # self.fromaddr,
  65. # ",".join(self.toaddrs),
  66. # self.getSubject(record),
  67. # formatdate(), msg)
  68. msg = MIMEMultipart()
  69. msg['From'] = self.fromaddr
  70. msg['To'] = ",".join(self.toaddrs)
  71. msg['Date'] = formatdate(localtime=True)
  72. msg['Subject'] = self.getSubject('')
  73. # fixed to deal with exception
  74. msg.attach(MIMEText(self.format(record).replace("\n", "<br>").encode('utf-8'), 'html', 'utf-8'))
  75.  
  76. # Prepare attachments
  77. for arg in self.attachment:
  78. attach_properties = os.path.splitext(os.path.basename(arg))
  79. with open(arg, 'r') as fp:
  80. if attach_properties[0].lower() in ['.jpg', '.png', '.gif', '.jpeg', '.bmp']:
  81. attachment = MIMEImage(fp.read())
  82. else:
  83. attachment = MIMEText(fp.read())
  84.  
  85. attachment.add_header('Content-Disposition', 'attachment', filename='.'.join(attach_properties))
  86. msg.attach(attachment)
  87.  
  88. if self.username:
  89. if self.secure is not None:
  90. smtp.ehlo()
  91. smtp.starttls(*self.secure)
  92. smtp.ehlo()
  93. smtp.login(self.username, self.password)
  94. smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())
  95. smtp.quit()
  96. except (KeyboardInterrupt, SystemExit):
  97. raise
  98. except:
  99. self.handleError(record)
  100.  
  101.  
  102. if __name__ == '__main__':
  103. MAILHOST = 'foo.smtp.org'
  104. SENDER = 'someone@somewhere.com'
  105. TO_ADDRS = ['me@somewhere.com', 'someoneelse@somewhere.com']
  106. SUBJECT = 'Subject'
  107. ATTACHMENT = 'some_file.txt'
  108.  
  109. log = logging.getLogger('')
  110. log.setLevel(logging.DEBUG)
  111. mail_attachment_handler = SMTPHandlerWithAttachment(mailhost=MAILHOST, fromaddr=SENDER, toaddrs=TO_ADDRS,
  112. subject=SUBJECT, secure=None, attachment=ATTACHMENT)
  113.  
  114. fmt = "%(msg)s"
  115. mail_attachment_handler.setLevel(logging.INFO)
  116. mail_attachment_handler.setFormatter(fmt)
  117. log.addHandler(mail_attachment_handler)
  118.  
  119. log.info("Did something")
Add Comment
Please, Sign In to add comment