DIY Email to SMS Gateway
Well, despite the ‘Wake on LAN’ being the ‘popular’ choice for my first how-to, as Murphy would have it, it’s not working now for some inexplicable reason. Hence the subject of this post will be getting emails to be automagically rerouted to your cell-phone by SMS.
Firstly, you unfortunately need to pay somebody to send you SMSes. Good choices in South Africa are WinSMS or BulkSMS. In both cases you sign up for an account and prepay a certain amount of SMSes. The example below uses BulkSMS.
Next, you need to set up a mail forwarder to execute a php script. I’m not entirely sure it’s possible with all hosts, but it is with Site5.
Create a mail account (I get bounce errors if the account doesn’t actually exist) eg “sms2me@mydomain.com”. Instead of forwarding to another email address, specify the following:
| /usr/local/bin/php /home/your_home_dir/path_to/sms2mail.php
Next you need the script to actually take the mail passed to it and ship it off through your third party gateway.
Disclaimer: This is code was pulled in from all over until I got the cursed thing to work. Requires curl libraries to do the form post. No warranties express, implied or otherwise apply. Some emails still come through with rich formatting etc, which uses up all your 160 available characters. I need to look into this at some stage.
#!/usr/bin/php
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
// handle email
$lines = explode(”n”, $email);
// empty vars
$from = “”;
$subject = “”;
$headers = “”;
$message = “”;
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."n";
// look out for special headers
if (preg_match(”/^Subject: (.*)/”, $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match(”/^From: (.*)/”, $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i].”n”;
}
if (trim($lines[$i])==”") {
// empty line, header section has ended
$splittingheaders = false;
}
}
$headers2 = “From: $fromrn” .
“Reply-To: $fromrn”;
mail(’###@gmail.com’, “[SMS] “.$subject, $message, $headers2);
$message = substr($message,0,155); // make sure it fits
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘http://bulksms.2way.co.za:5567/eapi/submission/send_sms/2/2.0′);
curl_setopt ($ch, CURLOPT_POST, 1);
$post_fields = “username=###&password=###&message=$message&msisdn=27#########”;
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response_string = curl_exec($ch);
curl_close($ch);
?>
Now back to getting my wake on wan to work again…


