views:

26

answers:

2

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?

Thanks!

+1  A: 

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.

Alex Howansky
The 2nd option may be more feasible since I'm not familiar with the shell / how to set up rules. I would like this to be pretty real time, so if I set up the IMAP it would have to do it every min. I'm not sure how much of a strain that would be on the server. Any suggestions on tutorials as to where I can find out how to write a PHP script to access the mailbox via IMAP?
Phil
+1  A: 

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

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

// open
$hMail = imap_open ("{mail.yourdomain.com:143/notls}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 );
Mark Steudel
Thanks! I should be able to figure out how to pull the body out, That doesn't seem too hard. I found this and I think it's right: echo imap_body($aFrom, $idx); and that would read the body and display it for each messaged during the loop
Phil
Nice good luck!
Mark Steudel
I also realized, I have access to the shell. I've never done anything with it, but can I put the above code in there and tell that code to run every few seconds instead?
Phil
Yup .. you probably want to look up CRON jobs on linux and I think schedule tasks on windows. The command on linux would probably be:php checkMail.php
Mark Steudel