How to Read/auto-process email using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Read/auto-process email using PHP

Post by Tony » Sun Nov 29, 2009 3:48 am

Here is a script that will read and process your mail. The script is written to match the subject line, allow you to do custom processing, then optionally delete the message. You can use this script to auto-process email requests. You can easily change the script to compare against other header fields. You have full access to the header fields and the message body. Use cron to kick it off every few minutes and you have auto mail processing. The script should be placed above the public directory to provide better security and to ensure no one runs the script from http.

Code: Select all

<?php

$server = "mail.yourdomain.com";
$user = "XXXXXX";
$password = "XXXXXX";
$subjectMatch = "Test";  // subject of the email messages you want processed
$delete = "Y";  // if delete is Y then processed mail will be deleted
 
$host = "{".$server.":143"."}"."INBOX";
$msgStream = imap_open($host,$user,$password);

$check = imap_mailboxmsginfo($msgStream);
$number = $check->Nmsgs;

function getHeader($msgStream,$msgNumber) {
  $mailheader = imap_headerinfo($msgStream,$msgNumber);
  $headerArray = array();
  $headerArray[0] = $mailheader->subject;
  $from = $mailheader->from;
  foreach ($from as $id => $object) {
    $headerArray[1]  = $object->personal;  // from personal
    $headerArray[2]  = $object->mailbox . "@" . $object->host;  // from address
  }
  $headerArray[3] = $mailheader->Date;
  return $headerArray;
}

function getBody($msgStream,$msgNumber){
   $body=imap_body($msgStream,$msgNumber);
   return $body;
}

$msgNumber = "1";
while ($msgNumber <= $number) {
  $headerArray = getHeader($msgStream,$msgNumber);
  $body = getBody($msgStream,$msgNumber);
  if ($headerArray[0] == $subjectMatch) { // check to see if the current message subject line matches what you want
    // do your special logic here
    // you have the header array and the body to work with
    // the echo line below is just for testing 
    echo "$headerArray[0]<br>$headerArray[1]<br>$headerArray[2]<br>$headerArray[3]<br>$body<br>";
    if ($delete == "Y") imap_delete($msgStream, $msgNumber);  // mark the current message for deletion
  }
  $msgNumber ++;
}

if ($delete == "Y") imap_expunge($msgStream);  // delete all messages marked for deletion 
imap_close($msgStream);

?>
As another example, if you wanted to process all mail over 3 days old you could use this test:

Code: Select all

if (strtotime($headerarray[3]) <= strtotime("-3 days")) { 
Post Reply

Return to “PHP & MySQL”