Question

I want to forward my bounced emails to a php script to deal with them. I am using.

 #!/usr/bin/php -q
 <?php

 // read from stdin
 $fd = fopen("php://stdin", "r");
 $email = "";
 while (!feof($fd)) {
$email .= fread($fd, 1024);
 }
   fclose($fd);

   // handle email
   $lines = explode("\n", $email);

  // empty vars
   $from = "";
    $subject = "";
    $headers = "";
    $message = "";
    $splittingheaders = true;

    for ($i=0; $i < count($lines); $i++) {
    if ($splittingheaders) {
    // this is a header
    $headers .= $lines[$i]."\n";

    // look out for special headers
    if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
        $subject = $matches[1];
    }
    if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
        $from = $matches[1];
    }
} else {
    // not a header, but message
    $message .= $lines[$i]."\n";
}

if (trim($lines[$i])=="") {
    // empty line, header section has ended
    $splittingheaders = false;
   }
   }

  ?>     

Works perfect! But how do I collect the "To" field in the bounced message? I've tried just adding a $to variable but it doesn't work.

Any help would be great,

thanks,

EDIT: Actually I need to get the "TO" field within the body of the message. - The email that it bounced back from. How do I pull apart the body of the message to take specific info? Should I create a special header with the person's email so that it is easier to get this info?

Was it helpful?

Solution

If you can create a custom header, that would be easiest. Otherwise, you need to match against your entire body for a particular pattern; and if your body text can vary, it could be difficult to make sure you are always matching the correct text.

Custom headers should begin with X-, so maybe do something like:

if (preg_match("/^X-Originally-To: (.*)/", $lines[$i], $matches)) {
    $originallyto = $matches[1];
}

But with X- headers, they are non-standard, so it is best to pick a name that is either

  1. Commonly used exclusively for the same purpose, or
  2. Not likely to be used by anyone else at all

One other thing you should be aware of; lines in a message should always end in "\r\n", so you might want to split on both characters (instead of just "\n") to ensure more consistent behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top