2019-03-27 16:06:23 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
|
|
|
|
from email import message_from_file
|
|
|
|
|
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import syslog
|
2019-03-29 10:54:07 +00:00
|
|
|
import urllib.request
|
2019-03-27 16:06:23 +00:00
|
|
|
|
|
|
|
hook_url = os.environ.get('SLACK_WEBHOOK_URL')
|
|
|
|
|
|
|
|
def main():
|
|
|
|
msg = message_from_file(sys.stdin)
|
|
|
|
try:
|
|
|
|
send_to_slack(dict(msg)['From'],dict(msg)['Subject'],msg.get_payload())
|
|
|
|
except(Exception):
|
|
|
|
syslog.syslog(syslog.LOG_ERR,"webhook failed, message was %s" % msg.get_payload())
|
|
|
|
|
|
|
|
|
|
|
|
def send_to_slack(fr,title,body):
|
|
|
|
title = title.strip()
|
|
|
|
body = body.strip()
|
|
|
|
fr = fr.strip()
|
|
|
|
|
|
|
|
slack_data = {
|
|
|
|
'text': "Email from " + fr,
|
|
|
|
'attachments': [
|
|
|
|
{
|
|
|
|
'title': title,
|
|
|
|
'text': body,
|
|
|
|
'fallback': body
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
2019-03-29 10:54:07 +00:00
|
|
|
req = urllib.request.Request(
|
2019-03-27 16:06:23 +00:00
|
|
|
hook_url,
|
2019-03-29 10:54:07 +00:00
|
|
|
data=json.dumps(slack_data).encode(),
|
|
|
|
headers={'Content-Type': 'application/json'},
|
|
|
|
method='POST'
|
2019-03-27 16:06:23 +00:00
|
|
|
)
|
2019-03-29 10:54:07 +00:00
|
|
|
|
|
|
|
with urllib.request.urlopen(req) as response:
|
|
|
|
if response.status != 200:
|
|
|
|
encoded_text = response.read()
|
2019-03-27 16:06:23 +00:00
|
|
|
syslog.syslog(
|
2019-03-29 10:54:07 +00:00
|
|
|
syslog.LOG_ERR, "Couldn't send webhook to slack: resp %s %s" % (response.status, encoded_text)
|
2019-03-27 16:06:23 +00:00
|
|
|
)
|
|
|
|
raise ValueError(
|
|
|
|
'Request to slack returned an error %s, the response is:\n%s'
|
2019-03-29 10:54:07 +00:00
|
|
|
% (response.status, encoded_text)
|
2019-03-27 16:06:23 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|
|
|
|
|
|
|
|
|