Apr 17, 2013 - Development    Comments Off

PHP Email Bounce Script

A lot of people have asked for this. This is the email bounce script I use. You will have to pipe all emails to this file.

<?
//opens the stream
$fd = fopen("php://stdin", "r");

$content = "";

//read the lines
while (!feof($fd))
{
    $content .= fread($fd, 1024);
}
fclose($fd);

$lines = explode("\n", $content);

$email = "";

//SPAM report from feedback loop
for($i=0;$i<count($lines);$i++)
{
    if(preg_match("/^Original-Rcpt-To:(.*)/", $lines[$i], $matches))
    {
        $email = trim($matches[1]);
        $mode = "spam";
        $type = 2;
        continue;
    }
}

//bounced back message from receiving server
if($email == "")
{
    for($i=0;$i<count($lines);$i++)
    {
        if(preg_match("/^Delivered-To:(.*)/", $lines[$i], $matches))
        {
            $mode = "bounce";
            $type = 1;
            $email = substr(trim($matches[1]),2);
            continue;
        }
    }
}

//failed message, MTA emailed a failed message
if($email == "")
{
    for($i=0;$i<count($lines);$i++)
    {
        if(preg_match("/^Remote host said:(.*)/", $lines[$i], $matches))
        {
            for($j=0;$j<count($lines);$j++)
            {
                if(preg_match("/^Return-Path:(.*)/", $lines[$j], $matches))
                {
                    if(strstr($matches[1], "=") !== false)
                    {
                        $mode = "bounce";
                        $type = 1;
                        $email = trim($matches[1]);
                        continue 2;
                    }
                }
            }
            continue;
        }
     }
}

//return-path format is user=website.com@mydomain.com
//convert this into the actually email, user@website.com
if($mode == "bounce")
{
    $email = substr($email,0,strpos($email,"@"));
    $email = str_replace("=", "@", $email);
}

if($email != "")
{
    if(strchr($email, "@") !== false)
    {
        $domain = substr($email,strpos($email,"@")+1);
        $sql = "SELECT id
                FROM donotemail
                WHERE LOWER(email) = LOWER('".fix($email)."')";
        $result = query($sql);
        if($result)
        {
            if(numrows($result) == 0)
            {
                $sql = "INSERT INTO donotemail
                        (email, type, thedate)
                        VALUES('".fix($email)."', '$type', CURDATE())";
                query($sql);
            }
        }
    }
}
?>

Comments Closed

Comments are closed.