Resources > Pipe emails into a PHP script
This little snippet will catch emails sent to a specific address, allowing you to then do any sort of manipulation on it. I successfully used it for over a year processing over 700 emails a day, extracting information from the email and inserting into a MySQL database. The script then produced a PDF document using the R&OS Class. Setup a forwarder and instead of an email address, put in the code in quotes below. This was easy to do in cPanel. I found this snippet on the internet somewhere, I cant remember exactly where.
#!/usr/bin/php -q
<?php
/*
You may need to play with chmod on this file
targetemail@yourdomain.co.uk, "|/usr/bin/php -q /home/user/public_html/this-script.php"
*/
$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;
}
}
$message;
/* do any further processing down here */
?>