add email_to_webhook

This commit is contained in:
Jeffrey Paul 2019-03-27 09:06:23 -07:00
parent 95b737c5fa
commit cfb1a5c8c3
4 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,4 @@
default: install
install:
bash ./install.sh

View File

@ -0,0 +1,22 @@
# send emails to root to slack
# prerequisites
`apt update && apt -y install git python3 make postfix`
# install
```
mkdir -p /etc/environment.d
git clone https://github.com/sneak/hacks.git /tmp/hacks && \
cd /tmp/hacks/forward-email-to-slack-webhook && \
make install
```
and
```
mkdir -p /etc/environment.d
echo 'https://hooks.slack.com/services/XXXXXX/XXXXXXX/xxxxxxxxxxxxxxxx' >
/etc/environment.d/SLACK_WEBHOOK_URL
```

View File

@ -0,0 +1,57 @@
#!/usr/bin/env python3
from email import message_from_file
import json
import os
import requests
import sys
import syslog
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
}
]
}
response = requests.post(
hook_url,
data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
syslog.syslog(
syslog.LOG_ERR, "Couldn't send webhook to slack: resp %s %s" % (response.status_code, response.text)
)
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,12 @@
#!/bin/bash
D="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cp $D/email_to_webhook /usr/local/bin/email_to_webhook
chmod +x /usr/local/bin/email_to_webhook
mkdir -p /etc/environment.d
echo "|/usr/bin/envdir /etc/environment.d /usr/local/bin/email_to_webhook" > /root/.forward
echo "now put your webhook url in /etc/environment.d/SLACK_WEBHOOK_URL"