How do I handle incoming mail with PHP?

Started by chinmay.sahoo, 07-05-2016, 04:38:22

Previous topic - Next topic

chinmay.sahooTopic starter

You've already seen that sending mail with PHP is no problem. But what about dealing with incoming mail using PHP? If your site is hosted on a Linux system, you'll be happy to hear that with a little tuning, it's easy to have PHP to examine incoming email.

Solution

In this solution, I'll assume that you have your site hosted on a Linux-based system, that you have command prompt access to the server and are able to run PHP from the command prompt, and that you're using sendmail to handle email on the server. Phew! It's a long list of requirements, I know, but this fairly common configuration greatly simplifies matters.

First things first: you need to place a file called .forward in your home directory. Use a text editor to write the following to the file (all on one line):

Quoteyou@yoursite.com "|/home/yourUserName/mailhandler.php"

Now, within the PHP script mailhandler.php, you can process incoming email for the you@yoursite.comemail address in any way you like. Here's an example script that detects incoming email from a particular address and sends a second notification email in response:

Quote#!/usr/bin/php
<?php
// Read the email from the stdin file
$fp = fopen('php://stdin', 'r');
$email = fread ($fp, filesize('php://stdin'));
fclose($fp);
// Break the email up by linefeeds
$email = explode("\n", $email);
// Initialize vars
$numLines = count($email);
for ($i = 0; $i < $numLines; $i++) {
// Watch out for the From header
if (preg_match("/^From: (.*)/", $email[$i], $matches)) {
$from = $matches[1];
break;
}
}
// Forward the message to the hotline email
if (strstr($from, 'vip@example.com')) {
mail('you@yourdomain.com', 'Urgent Message!',
'Check your mail!');
}
?>