hacks/forward-email-to-slack-webhook/email_to_webhook

61 lines
1.4 KiB
Plaintext
Raw Permalink Normal View History

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
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
}
]
}
req = urllib.request.Request(
2019-03-27 16:06:23 +00:00
hook_url,
data=json.dumps(slack_data).encode(),
headers={'Content-Type': 'application/json'},
method='POST'
2019-03-27 16:06:23 +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(
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'
% (response.status, encoded_text)
2019-03-27 16:06:23 +00:00
)
if __name__ == "__main__":
main()