PHP code to accept and decode incoming email message, pipe to script made easy
Posted On at by milanWe are already reached a point where we are using web 2.0 which is much more dynamic and user interactive. Also journey towards web 2.5 or 3.0 is already started. Now a days on daily basis in many systems we need email processing, i.e. data from incoming email message should automatically be inserted into database.
Lets see how incoming emails can be processed by custom scripts.
This is process of just two steps.
1. Write your own email processing script which decodes the incoming email messages and inserts data to db or a file
2. Set a forwarder in cpanel which redirects the incoming email to your personal email processing script
We will see and understand the both steps so the readers of this post can fully get able to process incoming email message.
STEP 1. Write Incoming Email processing script:-
Before moving to the actual script let me clear that your script must not output a single character on screen in order to work, as this script will run on backend when each email will be redirected to it through cpanel forwarder to script.
First line of the script will be out of PHP starting tag and it is the instruction which tells server the path of php which will be used to run this script. Please remember there must be nothing before this line in file, even not a space or any other character. Extension of file must always be .php
Lets move to script now each part is coming up with proper comments for making the process easier for you
#!/usr/bin/php -q
$htmlFound=0; // Database connection, in case you have to add data to db mysql_connect('localhost','username','password') or die('db error 1'); mysql_select_db('dbname') or die('db error 2');
//Stdin catches the whole text of incoming email puts it into $fd variable
$fd = fopen("php://stdin", "r"); // Read the first two MB of incoming email, (As in text and HTML mails message always resides in first two MB of data)
$fllg=0; $email = ""; $contents = "";
while (!feof($fd))
{
$contents .= fread($fd, 204800);
if($fllg==0)
{
$email=$contents; $fllg=1;
}
} fclose($fd);
//Add Slashes
$email=addslashes($email);
// Empty variables to avoid errors later on
$from = ""; $replyto = ""; $subject = ""; $headers = ""; $message = ""; $split = true;
// Break the e-mail into a line by line array to be put together again later on.
$lines = explode("\n", $email);
//Start splitting the headers and message from extracted email part.
for ($i=0; $i
// 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];
}
if (preg_match("/^Reply-To: (.*)/", $lines[$i], $matches))
{
$replyto = $matches[1];
}
}
else
{
$htmo=strpos($lines[$i],"Content-Type: text/html;");
if($htmo===false) //Plain text part is still being processed
{}
else
{
$htmlFound=1;
}//If in multipart messege Html part is started then set the varable to 1
$su=$subject[0];
$su.=$subject[1];
$su.=$subject[2];
$currLine=$lines[$i];
if($su=="RE:"||$su=="Re:")//check for replys -- dont show origional messages in replys.
{
//Same $htmlFound variable here is used to stop fetching the origional message from a reply if($currLine[0]==">")
{
$htmlFound=1;
}
if($currLine=="---- Original Message -----\n")
{
$htmlFound=1;
}
if($currLine=="---- Original Message -----")
{
$htmlFound=1;
}
}
if($htmlFound==0)
{ // not a header, but message
$message.=$lines[$i]."\n";
}
} if (trim($lines[$i])=="") { // empty line, header section has ended $split = false; } }
// Get the current time to keep the database on a standard time listing
$time = time();
//Pick out the sender's email without any extra characters just simple email which can be reused to put in db or send a reply etc
if(strpos($from, "<"))
{
$from_email = substr($from, strpos($from, "<")+1, strpos($from, ">")-strpos($from, "<")-1);
}
else if(strpos($from, "[mailto:"))
{
$from_email = substr($from, strpos($from, "[mailto:")+8, strpos($from, "]")-strpos($from, "[")-8);
}
else if(strpos($from, "[Mailto:"))
{
$from_email = substr($from, strpos($from, "[Mailto:")+8, strpos($from, "]")-strpos($from, "[")-8);
}
else if(strpos($from, "["))
{
$one=strpos($from, "[")+1;
$two=strpos($from, "]")-strpos($from, "[")-1;
$from_email = substr($from,$one, $two);
}
else if(($from[0]=="[")&&($from[1]=="m") && ($from[2]=="a") && ($from[3]=="i") && ($from[4]=="l") && ($from[5]=="t") && ($from[6]=="o") && ($from[7]==":"))
{
$one=strpos($from, "[mailto")+8;
$two=strpos($from, "]")-strpos($from, "[mailto")-8;
$from_email = substr($from,$one, $two);
}
else if(($from[0]=="[") && ($from[1]=="M") && ($from[2]=="a") && ($from[3]=="i") && ($from[4]=="l") && ($from[5]=="t") && ($from[6]=="o") && ($from[7]==":"))
{
$one=strpos($from, "[Mailto")+8;
$two=strpos($from, "]")-strpos($from, "[Mailto")-8;
$from_email = substr($from,$one, $two);
}
else if($from[0]=="[")
{
$one=strpos($from, "[")+1;
$two=strpos($from, "]")-strpos($from, "[")-1;
$from_email = substr($from,$one, $two);
}
else if($from[0]=="<")
{
$one=strpos($from, "<")+1;
$two=strpos($from, ">")-strpos($from, "<")-1;
$from_email = substr($from,$one, $two);
}
else
{
$from_email=trim($from);
}
//You are now done with email accepting script, following variables contain following data
//$from_email contains senders email neat and clean without extra characters
//$from contains sender's email full line with extra characters, use of variable $from_email is recommended over this
//$replyto contains email which can be used to reply sender, still use of $from_email is recomended
//$subject contains subject of incoming email
//$headers contain full header text
//$message contains the email message
//$time contains the current date/time info, which can be saved in your favorite/desired format.
//Now as I have specified all the extracted data variables, you can do anything with them, i.e. save email as a record in a db or save it in a text file. How you use these variables is fully up to you.
?>
So uptill now our email accepting script is complete. Save it in a file with extention as .php for example "handleMailz.php" and upload it inside an hosting account e.g. inside public_html folder.
STEP 2. Setup email forwarder to deliver emails to this newly developed script:-
Now next step is to set up a forwarder in cpanel which will redirect all incoming email messages to this script.
Lets see how to do this, considering the name of script file is "handleMailz.php" and it is uploaded in your hosting account's public_html folder.
- Login to your cpanel
- Under mail category click forwarders
- Click add forwarder button
- Now on target screen fill the add new forwarder form accordingly, in "address to forward" put in email address from which you want all email to be sent to the script.
Also under destination heading select third option pipe to program and add the destination of your script, path muct be relative to your home directory. e.g "public_html/handleMailz.php" in our case. Also see added cpanel image.
Now this script can be used in anysupport system to automatically accept incoming emails, parse required information and insert it into database.
Now its time to play with the script and if you find any difficulty in setting up the script feel free to contact me at "khurram1284pk [@]yahoo.com". I have customised and setup this script many times, so if you need my help in settingup this kind of forwarding, or integrating this into a web system effectively, I will be more than happy to help you. Just contact me using above email address.
Just Enjoy.