Piping incoming mails to a PHP program

| | Comments (0) | TrackBacks (0)

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).

0 TrackBacks

Listed below are links to blogs that reference this entry: Piping incoming mails to a PHP program.

TrackBack URL for this entry: http://www.megalinux.net/cgi-bin/mt/mt-tb.fcgi/19

Leave a comment

About this Entry

This page contains a single entry by Ram Prasad published on March 25, 2003 3:36 PM.

DNS monitoring using MRTG was the previous entry in this blog.

Installing PHP with GD is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by
Movable Type 4.01