Categories
GNU/Linux

GNU/Linux Procmail / Python Mail Alert Script for Telegram

Small script to send a telegram chat message to a user when new mail arives. Script uses procmail and a small python script to process the message and to send the alert alert message through a telegram bot api.

.procmailrc:#LOGFILE=/path/to/pmlog
.procmailrc:#VERBOSE=yes
.procmailrc:#LOGABSTRACT=all
.procmailrc:INCLUDERC=/etc/procmail-rc/filter-potentialproblem-rc
.procmailrc:INCLUDERC=/etc/procmail-rc/filter-potentialproblem2-rc
.procmailrc:INCLUDERC=/etc/procmail-rc/filter-spamassassin08-rc
.procmailrc:
.procmailrc::0Wc:
.procmailrc:| env python ./.pmscript.py
.procmailrc:
.procmailrc::0
.procmailrc:.mail/

.pmscript.py:import sys
.pmscript.py:import email
.pmscript.py:import httplib
.pmscript.py:import urllib
.pmscript.py:
.pmscript.py:# Contstants...
.pmscript.py:email_addresses = ['test@example.com', 'info@example.com']
.pmscript.py:key = "telegram_botkey"
.pmscript.py:userid = "telegram_userid"
.pmscript.py:headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
.pmscript.py:hostname = "api.telegram.org"
.pmscript.py:uri = "/bot" + key + "/sendMessage"
.pmscript.py:
.pmscript.py:# Read from stdin...
.pmscript.py:full_msg = sys.stdin.read()
.pmscript.py:msg = email.message_from_string(full_msg)
.pmscript.py:
.pmscript.py:# Get info from message...
.pmscript.py:mto = msg['to']
.pmscript.py:msubject = msg['subject']
.pmscript.py:mfrom = msg['from']
.pmscript.py:
.pmscript.py:# Check if e-mail in list...
.pmscript.py:for mailaddr in email_addresses:
.pmscript.py:  if mailaddr in mto:
.pmscript.py:    mrow = "[S6:NewMailAlert] \nFrom: " + mfrom + " \nSubject: " + msubject
.pmscript.py:    params = urllib.urlencode({'chat_id': userid, 'disable_web_page_preview': '1', 'text': mrow})
.pmscript.py:    connectie = httplib.HTTPSConnection(host=hostname, port=443)
.pmscript.py:    connectie.request("POST", uri, params, headers)
.pmscript.py:    resultaat = connectie.getresponse()
.pmscript.py:    if resultaat.status <> 200:
.pmscript.py:      print resultaat.status, resultaat.reason