Created
December 7, 2015 09:30
-
-
Save tschm/40a3f7d4c2e35d6cc86f to your computer and use it in GitHub Desktop.
Log handler based on Mailgun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import logging | |
class MailHandler(logging.Handler): | |
def emit(self, record): | |
send_message(subject=self.__subject, text=record, toAdr=self.__toAdr, fromAdr=self.__fromAdr, | |
mailgun=self.__mailgun, mailgunkey=self.__mailgunkey) | |
def __init__(self, level, format, subject, toAdr, fromAdr, mailgun, mailgunkey): | |
super().__init__() | |
self.level = level | |
self.formatter = logging.Formatter(format) | |
self.__subject = subject | |
self.__mailgun = mailgun | |
self.__mailgunkey = mailgunkey | |
self.__toAdr = toAdr | |
self.__fromAdr = fromAdr | |
def send_message(subject, text, toAdr, fromAdr, mailgun, mailgunkey, inline=None, | |
attachment=None): | |
files = list() | |
if attachment: | |
files.extend([("attachment", (f[0], open(f[1], mode="b+r"))) for f in attachment]) | |
if inline: | |
files.extend([("inline", (f[0], open(f[1]))) for f in inline]) | |
try: | |
return requests.post( | |
mailgun, | |
auth=("api", mailgunkey), | |
files=files, | |
data={"from": fromAdr, | |
"to": toAdr, | |
"subject": subject, | |
"text": text} | |
) | |
finally: | |
for f in files: | |
# List of tuples ("attachment or inline", (f[0], f[1])) | |
f[1][1].close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment