Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python program that pretends to be sendmail, sends to Slack webhook instead. Move to /usr/lib/sendmail and make executable (`chmod +x`)
#!/usr/bin/env python3
import sys
import json
import requests
slack_url = "<webhook URL>"
def get_subject(lines):
# Find subject
for line in lines:
if line.startswith('Subject:'):
subject = line.split(':', 1)[1]
return subject.strip()
except Exception as e:
print('get_subject exception', e)
return ''
def get_body(lines):
# Find body
for i, line in enumerate(lines):
# first blank line
if line == '\n':
body_lines = lines[i + 1:]
# list to string
return ''.join(body_lines)
except Exception as e:
print('get_body exception', e)
return ''
# Read from stdin until there is no more
lines = []
for line in sys.stdin:
subject = get_subject(lines)
body = get_body(lines)
text = f'*{subject}*\n{body}'
slack_data = {'text': text}
# Fire and forget
slack_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment