Passing Emails to ColdFusion Through PHP

by: Tom Mollerus

Passing Emails to ColdFusion Through PHP

I've written about how you can send data to ColdFusion from another task on your server, such as passing an email from your mail system to CF through a shell script. But what if the shell script doesn't work, or what if you're on Windows and don't have access to scripting at all? Well, you can also use PHP to pass the data. Here's how.

The script I've written is meant for passing data from QMail, where you can write what's called a dot-qmail file to tell the mail server to send the email data to another local process. There are probably ways of doing the same thing in a Windows environment, but I'll leave that up for others.

First, we need to tell our mail server to pass the email to a script instead of delivering it normally. For QMail, we do that with a ".qmail" file. The name of the file starts with .qmail, has a dash, and then has the name of the user portion of the email address. For example, if we were to intercept emails sent to cli@example.com, our .qmail file would be named ".qmail-cli". Inside the file, we tell the mail server to pass information with a pipe "|" , then the path to the PHP binary, and then the full path of the script we're going to write, like so:

.qmail-cli

| /path/to/php /path/to/callCF.php

Now for the contents of our script, callCF.php. Our script is going to read the email from PHP's standard input, then URL-encode it, and then finally use cURL to post it as a FORM variable named "data" to a ColdFusion page:

callCF.php

// Initialize parameters
$email = '';
$url = '[Enter your ColdFusion URL here]';


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


// URL-encode the data
$email = urlencode($email);
$data = array('data' => $email);


// Use cURL to send the data to ColdFusion
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
curl_close($ch);

?>

cURL posts the email to your CF script, with a form variable named "data". After that, you've got the power of good old ColdFusion to process it however you like. And I promise that my follow-up posting explaining my technique for parsing through emails will be coming soon.

Please feel free to download and use this script yourself.



Article published Thursday, 3rd January 2008
© 2008 NetVisits, Inc. All rights reserved.