Home >> Snippet List >> Snippet

Name
Automatically process email
Description
Automatically process an email with attachment(s) using PHP and PEAR Mail class
PHP Snippet
<?PHP
 
/*
Prerequisites:
Linux/BSD
PHP with CLI enabled
PEAR
Sendmail with individual user account
 
Aim: Save attachments to server storage.
 
1. Setup sendmail account to forward to PHP script.
 
In the home directory (/home/user) on the foo.bar machine make 
and edit a file called ".forward". In this file put in the 
following.
 
|"/dir_to_php_script/process.php"
 
This will forward any email sent to user@foo.bar.com to the 
php script.
 
2. PHP script to process email "/dir_to_php_script/process.php"
[Don't forget to chmod 755 process.php]
 
*/
 
// begin contents of process.php
#!/usr/local/bin/php
<?PHP
// Need PEAR installed
INCLUDE('Mail.php');
INCLUDE('Mail/mime.php');
REQUIRE_ONCE 'Mail/mimeDecode.php';
 
// read email using stdin
$fd = FOPEN("php://stdin", "r");
$email = "";
WHILE (!FEOF($fd)) {
        $email .= FREAD($fd, 1024);
}
FCLOSE($fd);
 
$params['include_bodies'] = TRUE;
$params['decode_bodies']  = TRUE;
$params['decode_headers'] = TRUE;
 
$message=NEW Mail_mimeDecode($email);
$mailObj=$message->decode($params);
 
// Who is it from
$from=$mailObj->headers['from'];
// Get Subject
$subj=$mailObj->headers['subject'];
// Get Message Body
$body=$mailObj->parts[0]->body;
$gather="From:$from\nSubject:$subj\nBody:$body";
 
 
// Get and Save the Attachments
FOREACH($mailObj->parts AS $key=>$val):
        $tmpObj=$mailObj->parts[$key];
        $tmp=$tmpObj->d_parameters['filename'];
        IF(!EMPTY($tmp)):
                $fd = FOPEN($tmp, 'w');
                FWRITE($fd, $tmpObj->body);
        ENDIF;
 
} //endforeach;
 
// end of contents of process.php
?>