« Contextual Form Field Labels with ColdFusion | Main | Want To Enjoyably Waste a Few Hours? Then Go to The Animated GIFs Group on Virb. »

Writing an Email Autoresponder Script with PHP

It's very convenient for users to be able to communicate with web applications (or businesses) via email, but it's not always easy for the employees of the company to respond. Some of the email requests could be complex, and others could be simple but occur very frequently. So it's a real advantage when we can write scripts to respond to user emails for us. Here are some of the many uses I've found for autoresponder scripts:
  • Distributing emails to a dynamic, user-defined list of recipients;
  • Handling unsubscribe requests and subsequent feedback;
  • Auto-responding to support requests to let the user know their email has been received;
  • Parsing email campaign bouncebacks and marking hard bounces as bad email addresses, and;
  • Adding senders to a newsletter recipient list.

Fortunately, PHP fits nicely into the role of a scripting language which can talk to your application databases (to get user data), generate emails, and be called as a command-line interface by your mail program. That's the most important part-- many web languages support reading and sending emails and talking to your database, but few are accessible both as application servers and as command-line programs. I'll explain how to write such a script next.

First you need to tell your mail server to run a specific script every time an email is received for a specific account. For Qmail on Linux, you'd write what's referred to as a "dot-qmail" file. The filename should start with .qmail, then have a dash, and then the exact name of the email account that you want the script to run for. For instance, if you wanted an autoresponder for your support emails, you would create a file named .qmail-support:
| /path/to/php /path/to/autoresponder-script.php
Now for the PHP script. At the top of our script we need to initialize variables.
// Initialize variables
$from = "";
$to = "";
$cc = "";
$bcc = "";
$subject = "";
$allheaders = "";
$otherheaders = "";
$message = "";
$splittingheaders = true;

Then we add code that pulls the email in from standard input (don't worry if you don't know what standard input is; it's the way that PHP automatically gets data in command line mode).

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

Now copy the email into an array by splitting it by lines. This makes it easier to loop over.

// Parse the email line by line into an array 
$lines = explode("\n", $email);

Now parse the email into variables that represent individual header lines as well as the body.

// For each of the lines in the email
for ($i=0; $i

Now there you have what you really want.. all of the information in the email has been broken up into identified chunks. At this point you can run database lookups on the email address or on information in the header, or you can reply to the sender, and/or you can forward the email on. (Consult the PHP docs for more information on how to customize the mail() function.)

// Send an autoresponse back to the user
mail("$from", "Responding subject", "", "From: Responder Name ");

The rest is up to you. Of course, when creating an autoresponder like this, you always take the chance that you're going to get caught in a mail loop (where the autoresponse you send gets an autoresponse back, which gets an autoresponse, which gets an autoresponse, and so on ad infinitum). You definitely don't want this to happen-- so I use two tactics. First of all, I filter out autoresponses to the autoresponder's domain with a simple conditional statement like so:

// If the user isn't from our domain
if(!strpos($from, '@yourdomain.com'))  {
     // Then send an autoresponse back to the user
     mail(....);
}

Secondly, I keep a list of the latest 10 emails sent to the autoresponder script. If the current from address is 8 of the last 10 entries, then I suppress further responses.

// Read in the list of recent emails from the filesystem
$recentMatches = 0;
$fd = fopen("/path/to/recentList.txt", "r");
while (!feof($fd)) {
    $recentList .= fread($fd, 1024);
}
fclose($fd);

$lines = explode("\n", $recentList);
for ($i=0; $i 0 || count($lines) < 10)
		fwrite($fd, $lines[$i] . "\n");
}
fwrite($fd, $fromEmail . "^" . $date);
fclose($fd);

// If the user isn't from our domain and hasn't sent too many recent emails
if($recentMatches < 8 && !strpos($from, '@yourdomain.com'))  {
     // Then send an autoresponse back to the user
     mail(....);
}

Oh! And don't forget to forward the original email to someone within your organization.

// If the user isn't from our domain and hasn't sent too many recent emails
if($recentMatches < 8 && !strpos($from, '@yourdomain.com')) {
	// Forward the email
	mail("First Last ", "$subject", "$message", "From: $from\n");
	mail("First Last ", "$subject", "$message", "From: $from\n");
}

Download the complete script and do whatever you like with it. It will take some customization of names, emails/domains, and system paths to work for you, but if it can save you work in the long run it's well worth your time to set up.

Comments (4)

thanks for script php autoresponder.

Very useful. Thanks. It's amazing how simple it is, and there are people out there selling scripts like this for $50, or autoresponder services at $10 per month.

wow, i love it! you're a genius!

Hi!

I wonder if this is also applicable to flash email form.

I created a flash email form to a site I am trying to create, and now wanting to have an auto respond function. The situation right now is that, if I send an email FROM my yahoo to the email add where I created an auto reply function, the auto reply works, but when I use the flash email form from the site, I don't get any auto respond. Please help.

Post a comment


Type the characters you see in the picture above.