email – Processing incoming e-mail with PHP Script – Education Career Blog

So I’m trying to figure out how to send an email to an address for example, [email protected] and instead of the e-mail going to there it would be instead sent or forwarded to a script that I create to read the contents of the email and store the contents into a database. Any suggestions on how to do it in PHP?



Here’s some code you could use to get you going:

// set user to check
$strUser     = "username";
$strPassword = "password";

// open
$hMail = imap_open ("{}INBOX", "$strUser", "$strPassword");

// get headers
$aHeaders = imap_headers( $hMail );

// get message count
$objMail = imap_mailboxmsginfo( $hMail );

// process messages
for( $idxMsg = 1; $idxMsg <= $objMail->Nmsgs; $idxMsg++  )
    // get header info
    $objHeader = imap_headerinfo( $hMail, $idxMsg );

    // get from object array
    $aFrom = $objHeader->from;

    // process headers
    for( $idx = 0; $idx < count($aFrom); $idx++ )
        // get object
        $objData = $aFrom $idx ;

        // get email from
        $strEmailFrom = $objData->mailbox . "@" . $objData->host;

        // do some stuff here

    // delete message
    imap_delete( $hMail, $idxMsg );

// expunge deleted messages
imap_expunge( $hMail );

// close
imap_close( $hMail );


Two options:

1) If you have access to the shell on the recipient email server, you can set up a rule to fire a script (like via procmail or the like) whenever a new message is received.

2) You can allow the email to drop into the mailbox as normal, then write your PHP script to access the mailbox via IMAP, pull the new messages, process them, then delete them. And then run the thing by cron every few minutes.

Leave a Comment