In a previous post, I described how to set up SMS notification for email. This solution had one large disadvantage out of the box, however: Emails with large bodies of text are sent to the phone as multiple SMS messages until it reaches a max SMS limit or the end of the email message. But it’s not ideal to think you’ll want to read entire email messages via texts, so instead I’m going to jump right into showing you how to format the message into more useful shorthand.
Note: Each email setup will be different depending on hosting situation but this post will largely deal with hosting where you have permissions to run scripts. Major hosts such as Yahoo, Gmail and Hotmail each have their own unique solution. I may post a Gmail solution in the near future using the Google App Scripts API.
PHPMailer
PHP has a mail() function but it’s awful compared to using a library, such as PHPMailer. PHPMailer provides an API for formatting outgoing emails which is especially useful to avoid having to construct email headers from scratch. It also provides more advanced features such as HTML emails, sending email attachments, and SMTP authentication. Plus it’s incredibly simple to install and can be downloaded here from the official github page (which also includes API documentation).
Install is as simple as extracting and uploading to your web disk in your home directory. Be sure to keep it out of your public_html directory.
Pipe Program
Now that PHPMailer is installed, let’s take a look at the script emailscrape.php:
#!/usr/bin/php -q <?php require_once('../PHPMailer_5.2.0/class.phpmailer.php'); $credentials = require_once('../mail/mailconfig.php'); //Read contents of email 1024 limit $fd = fopen("php://stdin", "r"); $email_content = ""; while (!feof($fd)) { $email_content .= fread($fd, 1024); } fclose($fd); try { $mail = new PHPMailer(); // Initialize PHPMailer object $body = date("D j/n h:iA"); // Grab timestamp $mail->IsSMTP(); // Telling the class to use SMTP $mail->SMTPDebug = false; // SMTP debug information for testing // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Host = $credentials['host']; // Set the SMTP server $mail->Port = $credentials['port']; // Set the SMTP port for the server $mail->Username = $credentials['username']; // SMTP account username $mail->Password = $credentials['password']; // SMTP account password $mail->IsHTML(false); // Not sending HTML email $mail->Body = $body; // Set message body to timestamp $to = $credentials['destination']; $mail->AddAddress($to); // Set destination email address //Initialize subject, default header to true and explode email by line $subject = ""; $is_header= true; $lines = explode("\n", $email_content); //Check each line for Subject for ($i=0; $i < count($lines); $i++) { if ($is_header) { // Split out the subject portion if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) { $subject = $matches[1]; } //Split out the sender information portion if (preg_match("/^From: (.*)/", $lines[$i], $matches)) { $from = $matches[1]; } } if (trim($lines[$i])=="") { // empty line, header section has ended $is_header = false; } } $mail->Subject = $subject; $mail->setFrom($credentials['username'], $from); //Send mail and check for errors if($mail->Send()){ //echo 'Email Successfully Sent!'; } else { echo 'Email Sending Failed!'; } //Catch exceptions and output errors } catch (phpmailerException $e) { echo $e->errorMessage(); } catch (Exception $e) { echo $e->getMessage(); } ?>
Program Breakdown
This script handles three functions:
1. Reads the email
2. Parses the email header info.
3. Constructs and sends our new formatted email
So any email piped into this script is read, the header fields ‘Subject’ and ‘From’ are found using regex matching and their contents are stripped, a new email is constructed that’s more SMS friendly and is forwarded on to the email recipient (in this case a phone via SMS).
There is one line that is especially important:
#!/usr/bin/php -q
This line is called a “shebang” and allows this script to be run as a shell command, the path defining the location of the compiled binary for the version of php that you want to interpret your script. This location should be default across hosting providers where PHP is installed. If you are having problems but have SSH access you can run the UNIX which command:
which php
to find the path to the executable for your shebang, otherwise contact your provider.
Upload Program To Web Server
Upload this script to your web disk outside of your public_html folder and with the chmod permissions set to 0700.
In my script I load in some of the more sensitive configuration details from a configuration file with the same permissions and also located elsewhere outside of my public_html folder.
Set Up Forwarding To Program
Now we rather simply need to set up the forwarding from our email address to the program. The address to forward from there is handled in the script (Note: If you already have a forwarder set up to forward directly to the phone’s email from following my previous post then delete that forwarder).
And there you have it!
Any emails received will now have a copy formatted and forwarded to your phone as soon as they’re received. I encourage you to experiment with various formatting options not just the timestamp example I used that fits my needs. Keep in mind that if there are any errors or other output from the script, a bounce back message will be sent to the original email sender. My advice is to test it thoroughly by sending yourself email from another email address and be sure to print errors to a log file rather than echoing them.
Leave a Reply