Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Email

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Incoming Email Sent to PHP Script

An incoming email can be sent to a PHP script on your server — your custom PHP script. Consider what could you do with functionality like that!

The PHP script the email is forwarded to can make a log, update a web page, record a vote — whatever you want it to do that can be done with PHP.

Here are a few imagination-stimulating suggestions.

  • Auto-reply with relevant content. If an email to a certain address contains specific key words or phrases, (1) the PHP software can respond with information that may answer a question or help resolve an issue, or (2) send a copy of the email to an address of someone best equipped to handle the issue.

  • Provide specific information by email. Send an email to a dedicated email address with a request in the subject line. The server responds with the content that was requested. (An example is Wordsmith.org's service.)

  • Relay email to online support dashboard. Some (perhaps most) online support software will send email to the person when they start or update a ticket. Replies from those emails can be inserted into the support software database just as if the replies were done via the support dashboard.

  • Subscribe-to-list functionality. An email to a special address can subscribe the "From" address to a newsletter or announcement list.

Although there are additional ways to send an incoming email to a PHP script, this article specifically describes how to do it with cPanel on a Unix or Linux server.

The PHP script on the server that email is forwarded to may process subject lines and/or body content to determine actions to take.

The subject line may be used to indicate a preference, as an example. Or may be processed to determine how to respond — with store hours, additional contact information, driving directions, special of the day, or other information.

The email body content may be scanned for clues what to publish on a web page or store in a database, or for key words to construct an automatic reply.

The from and reply‑to lines may be processed, too — perhaps for sending an automated response or for storing the information in a database.

One thing about providing information by email is that you don't have to ask for an email address to send things to. It is embedded in the email itself that the person sent to your software.

Implementing Email-to-Script Functionality

There are two things that need to be done.

  1. The PHP Script

    When an email arrives, it contains both the header lines and the body content of the email. The PHP script can be customized to handle those as you wish.

  2. The Forwarding

    This is step-by-step instructions for forwarding the incoming email to your custom PHP script using cPanel.

The PHP Script

To make the PHP script available to cPanel for incoming email, there are some specific requirements.

  1. The first line of the script needs to have a hashbang line, sometimes called a shebang line. (Specific instructions follow.)

  2. The PHP script needs to have specific permissions and optionally may be installed below the document root directory. These will be explained in the instructions.

We'll address the hashbang line first. Then present an example PHP script. And, finally, talk about where the script may be installed and the permissions it needs.

The hashbang line —

The first line of the PHP script to receive the email is the hashbang line. (The script is further below.) In essence, the hashbang line tells the server where the server php interpreter software is at, but it also has a few more characters. Here is its construction:

#!PHPLOCATION -q
  • The #! characters — hash character and banger (exclamation mark) — tell the server that what follows is the location of the software to be used to run the code in this file.

  • PHPLOCATION represents the location of the php interpreter software. Further below, I'll show you how to determine the location of the software so you can replace PHPLOCATION with the correct information.

  • The -q characters tell the php software to suppress headers. That's so you don't get an extraneous and inappropriate email bounce message every time your script receives an email.

Now, let's find the location of the server php interpreter software so PHPLOCATION can be replaced.

How to Find the Location of the Server PHP Interpreter Software

Here are three methods. At least one of them should work. (The location of the php interpreter is likely to be /usr/bin/php or /usr/local/bin/php but may be in some other location.)

  1. For this method, upload this one-line PHP script on your domain as which.php and then type its URL into your browser's address bar.

    <?php echo `which php`; ?>
    

    Note that the above ` characters are backticks, not quotation marks or apostrophes.

    When you type the URL of which.php into your browser's address bar, the browser window should publish the server php interpreter software location. If it does not, use one of the next two methods.

  2. To use this second method, upload this one-line PHP script on your domain as which.php and then type its URL into your browser's address bar.

    <?php system('which php'); ?>
    

    The browser window should display the server php interpreter software location. If it does not, use the next method.

  3. For this third method, upload this one-line PHP script on your domain as which.php and then type its URL into your browser's address bar.

    <?php echo exec('which php'); ?>
    

    The browser window should display the server php interpreter software location.

If none of those three methods work, then your hosting company will need to provide the location of the php interpreter for your server.

Let us assume that /usr/local/bin/php is the location of your php interpreter. In that case, PHPLOCATION is replaced with the /usr/local/bin/php location.

#!/usr/local/bin/php -q

The hashbang line must be at the very top of your PHP script.

An example PHP script —

The example PHP script contains code to log a copy of the email that the script receives and to send a copy to another email address. They are examples that you may delete or expand on.

The example script is only that, an example. After the functionality has been implemented, then either replace the example script with your own or modify the example script to suit your purposes.

Notes are below this example PHP script source code.

#!/usr/local/bin/php -q
<?php
/*
Forwarded Email Handler
Version 1.0, July 23, 2021
Will Bontrager Software LLC
https://www.willmaster.com/
*/
// Note, the next 3 lines are required. They grab the email that is forwarded to the script.
$ReceivedEmail = '';
$stdin = fopen('php://stdin','r');
while( ($line = fgets($stdin)) !== false) { $ReceivedEmail .= $line; }

// Example method to store the arrived email in a plain text log file.
$Subdirectory = 'log'; // Directory must exist and may need 777 permissions.
$FileName = 'EmailsReceived.txt';
$AboveEmail = 'Received: ' . date('r') . "\n";
$BelowEmail = "\n======================================\n";
file_put_contents(__DIR__."/$Subdirectory/$FileName","$AboveEmail$ReceivedEmail$BelowEmail",FILE_APPEND);

// Example method to send a copy of the received email to another email address.
$ToAddress = "name@example.com";
$FromAddress = "name@example.com";
$Subject = "Copy of Received Email";
mail($ToAddress,$Subject,$ReceivedEmail,"From: $FromAddress");

// The next line is required to be the last line the script runs; Otherwise, it may cause an extraneous and inappropriate email bounce email.
exit;
?>

Notes —

The first line
#!/usr/local/bin/php -q
is required. If the location of the php interpreter software on your server is not /usr/local/bin/php then update the location accordingly.

The 3 green lines below the PHP script header are required. They receive the email forwarded to the script. The email content is stored in variable $ReceivedEmail

The 5 red lines are optional. They may be removed or expanded on. The lines store the received email in a log file. There are 4 variables that may be changed or used as is.

The 4 purple lines are optional. They may be removed or expanded on. The lines send a copy of the received email to an email address. The value of the $ToAddress variable needs to be changed to a valid email address. Same with the $FromAddress variable. The $Subject variable is the subject line of the email being sent and may be changed or left as is.

The last program line, exit; should be present. Without it, the PHP script may attempt to echo content toward the end of the file. When it does that, the system sends a bounce email to you which, in this case, is likely to be both extraneous and inappropriate.

Where to install the script —

First, save the above example PHP script as EmailHandler.php (or other *.php file name).

The EmailHandler.php script may be installed in the public document area or one directory below the public document area. I'll explain.

The public document area is where your website web pages are at. The directory location is /home/user/public_html/ and there may be subdirectories. (user represents the username of your domain.)

One directory below the public document area is /home/user/

The EmailHandler.php script may be installed in /home/user/ or a subdirectory, either public_html or a subdirectory you create. These are all valid locations:

/home/user/EmailHandler.php
/home/user/mysubdirectory/EmailHandler.php
/home/user/public_html/EmailHandler.php
/home/user/public_html/mysubdirectory/EmailHandler.php

When has been installed, do these steps:

  1. Give the EmailHandler.php file 700 permissions. This is necessary so the server can run the script without going through HTTP.

  2. In the directory where EmailHandler.php is installed, create subdirectory log — so EmailHandler.php can write a copy of the emails it receives. Note that subdirectory log may need 777 permissions so EmailHandler.php can write to it.

EmailHandler.php is now installed and ready.

The Forwarding

At this point, EmailHandler.php is installed in

/home/user/EmailHandler.php
/home/user/mysubdirectory/EmailHandler.php
/home/user/public_html/EmailHandler.php
/home/user/public_html/mysubdirectory/EmailHandler.php

Note the parts that are underlined in the above locations. The relevant underlined part will be used in cPanel. Instructions follow.

Before continuing, let me mention this: cPanel changes things. It might have been changed since this article was published. Current information should be available at this cPanel document.

Log into cPanel and tap the "Forwarders" icon.

Then, the "Add Forwarder" button. (Not "Add Domain Forwarder".)

To add the forwarder that will send incoming email to your EmailHandler.php script, first specify the email address that will be forwarded.

Then, open the "Advanced options" section.

In the "Advanced options" section, you'll see a "Pipe to a Program" field. In that field, type the location of EmailHandler.php relative to the /home/user/ directory. Do not begin the location with a "/" (slash) character. According to the example locations in the box further above, the locations might be one of these:

EmailHandler.php
mysubdirectory/EmailHandler.php
public_html/EmailHandler.php
public_html/mysubdirectory/EmailHandler.php

Save the forwarder and you should be good to go.

Test by sending an email to the email address you set up for forwarding to the email-processing PHP script.

If the script has a coding error or there is something else amiss, you should get an email bounce message with information about what went wrong. The information can be used to do whatever needs to be done.


Email can be forwarded to a script on the server.

Email-processing PHP scripts can be written to do what you want them to do. There are lots and lots of possibilities.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC