Pages

Automatically Process Email


Snippet Name: Automatically process email
Description: Automatically process incoming email with attachment(s) using PHP and PEAR Mail class.



<?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
?>

No comments:

Post a Comment