Admins eHow SysAdmin Tips & Tricks

April 26, 2017

Email to Telegram gateway

Filed under: PHP — Tags: , , , — admin @ 7:21 am

1.Create your own Telegram bot based on this tutorial :
https://www.domoticz.com/wiki/Telegram_Bot
or this one :
https://www.forsomedefinition.com/automation/creating-telegram-bot-notifications/
2.Create an email forwarder in cPanel and pipe it into a PHP script. make sure the script is executable (755 permission).
3.Here is the php script that will forward the email to your telegram bot :
Dont forget to adjust $url variable in telegram function based on first step.

#!/usr/local/bin/php -q
<?php
function mailRead($iKlimit = "")
{
	if ($iKlimit == "") {
		$iKlimit = 1024;
	}
	$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
	$fp = fopen("php://stdin", "r");
	if (!$fp) {
		echo $sErrorSTDINFail;
		exit();
	}
	$sEmail = "";
	if ($iKlimit == - 1) {
		while (!feof($fp)) {
			$sEmail .= fread($fp, 1024);
		}
	}
	else {
		while (!feof($fp) && $i_limit < $iKlimit) {
			$sEmail .= fread($fp, 1024);
			$i_limit++;
		}
	}
	fclose($fp);
	return $sEmail;
}

function telegram($m)
{
	$url = 'https://api.telegram.org/botxxxxxxx:xxxxxxxxx/sendMessage?chat_id=xxxxx&text=';
	$url .= urlencode($m);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);
}

$mail = mailRead(4096);
$lines = explode("\n", $mail);

$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;

for ($i = 0; $i < count($lines); $i++) {
	if ($splittingheaders) {
		$headers .= $lines[$i] . "\n";
		if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
			$subject = $matches[1];
		}
		if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
			$from = $matches[1];
		}
		if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
			$to = $matches[1];
		}
	}
	else {
		$message .= $lines[$i] . "\n";
	}
	if (trim($lines[$i]) == "") {
		$splittingheaders = false;
	}
}

telegram("From: $from\nSubject: $subject\nMessage: $message");
?>

Powered by WordPress