Process an email automatically with PHP and PEAR Mail

Automatically processing an email with attachment(s) using PHP and PEAR Mail class
from this blog entry

Prerequisites:
Linux/BSD
PHP with CLI enabled
PEAR
Sendmail with individual user account

Aim: Save attachments sent to christian@foo.bar.com to server storage.

1. Setup sendmail account to forward to PHP script.

In the home directory of christian(/home/christian) 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 christian@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

This entry was posted in Programming. Bookmark the permalink.