Piping incoming mails to a PHP program

Would you like to parse incoming mail using your PHP program ?
Would you like to store incoming mails to your database ?
Thanks to Gijs van Tulder I was able to set it up on my mail server.

The following is the PHP code for it (say /home/ram/mailparse)

#!/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;
}
}

?>

Now, to configure sendmail, create a symlink in /usr/adm/sm.bin (ln -s /home/ram/mailparse /usr/adm/sm.bin/mailparse). Add the following line to your /etc/mail/aliases(where mails to helpdesk@domain.com is parsed by the php program):
helpdesk:         “| /home/ram/mailparse”
regenerate the aliases database
# newaliases

Done. Any mail to helpdesk with be parsed by the php program ( and stored to the database, if required).