PHP Email Pipe, Send Email to a PHP Program

Email piping allows emails to be processed via a script on the server instead of them being sent to a mailbox. This process can be seen in many support ticket systems allowing clients to create new support tickets via emails which are sent to a specified email address.

Step One – Setting up the Server

Login to your hosting cPanel, under the mail heading look for a link similar to Default Address , this section allows you to route all your email addresses for the domain name. under the Advanced Options button check the radio box next to Pipe to a Program. Enter the name of the script that you wish to use as a Email Pipe, for this example we will use emailpipe.php

Step Two – Creating the Pipe

Under the account you set up the email pipe script to run, in the home directory for this account add a new file called emailpipe.php, right click this file in your ftp editor and change the file permissions to 755, or ssh to the server and chmod 755 the same file.

Step Three – Capturing the emails

Open emailpipe.php in your favourite text editor and add the following code, making sure there are no spaces before or after the <?php or ?>.

#!/usr/bin/php -q
<?php
$email_msg = ''; // the content of the email that is being piped
$email_addr = [email protected]'; // where the email will be sent
$subject = 'Piped:'; // the subject of the email being sent
 
// open a handle to the email
$fh = fopen("php://stdin", "r");
 
// read through the email until the end
while (!feof($fh)){
	$email_msg .= fread($fh, 1024);
}
fclose($fh);
 
// send a copy of the email to your account
mail($email_addr, $subject, "Piped Email: ".$email_msg);
?>

PHP Explination

The first line of the code, tells the email forwarder that the script it is about to run is a PHP script, and links to your php location (you may need to change the location e.g. #!/usr/local/bin/php -q).
The -q at the end of the first line tells the compiler not to output errors (this stops emails being bounced back to the sender if something goes wrong).

#!/usr/bin/php -q

This next section of code reads from the emails temporary file, adding it to the variable $email_msg. You can read more about the PHP file() functions.

$email_msg = '';
$fh = fopen("php://stdin", "r");
// read through the email until the end
while (!feof($fh)){
	$email_msg .= fread($fh, 1024);
}
fclose($fh);

Now that we have the email in a variable, lets send it to our email address using PHP mail() function.

// send a copy of the email to your account
mail($email_addr, $subject, "Piped Email: ".$email_msg);


Liked this article? help spread the word.