How do I handle incoming mail with PHP?

Author Topic: How do I handle incoming mail with PHP?  (Read 372 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 139
  • Karma: 0
    • No Addiction
How do I handle incoming mail with PHP?
« on: 07-05-2016, 04:38:22 »
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.


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):

Quote "|/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:

// Read the email from the stdin file
$fp = fopen('php://stdin', 'r');
$email = fread ($fp, filesize('php://stdin'));
// 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];
// Forward the message to the hotline email
if (strstr($from, '')) {
mail('', 'Urgent Message!',
'Check your mail!');


Related Topics

  Subject / Started by Replies Last post
4 Replies
Last post 09-15-2011, 05:00:01
by sufalamtech
6 Replies
Last post 12-22-2011, 04:26:28
by smith
5 Replies
Last post 08-14-2015, 04:10:30
by ajaymehta588
1 Replies
Last post 07-18-2016, 04:03:20
by TomClarke
3 Replies
Last post 09-23-2016, 04:27:03
by manishaverma