Sending email from FileMaker via PHP, revisited
Wednesday, October 22nd, 2008We last looked at this a few months ago, but have been revisiting it to come up with something a little more robust. Notes:
- there’s a good overview of using PHP with FM at the sixfriedrice blog.
- the API for FileMaker’s PHP interface is available at http://YOURSERVER.URL:16000/docs/PHP%20API%20Documentation/index.html
- I’d missed this last time around, but accounts & permissions are a little funky. fmphp needs to be added to the Extended Privileges of the database you’re trying to get to, and must have the same privilege set as the account you’re connecting as.
- The solution we settled on is a CLI PHP script running hourly, checking for mail to send. Launchd would be the logical way to do the scheduling, but always drives me nuts. Fortunately the server in question has cron set up (so much simpler!)
The code we’re more or less using:
#!/usr/bin/php
<?php
set_include_path(get_include_path() . PATH_SEPARATOR .
'/Library/FileMaker Server/Web Publishing/publishing-engine/php/lib/php/');
require_once('FileMaker.php');
echo "PHP email-sending-script, running at " .
date('m/d/Y H:i') . "\n";
$layout = 'Outgoing_Email';
$fm = new FileMaker('Layout Name');
$fm->setProperty('username', 'your filemaker username');
$fm->setProperty('password', 'your filemaker password');
$findCmd =& $fm->newFindCommand($layout);
$findCmd->addFindCriterion('Sent_Flag', '< 1');
$result = $findCmd->execute();
if (FileMaker::isError($result)) {
if ($result->code == 401) {
exit("No emails to send.\n");
} else {
exit("trouble: " . $result->message . "(" . $result->code . ")");
}
}
$records = $result->getRecords();
foreach($records as $record) {
echo "To: " . $record->getField('Recipient') . "\n";
echo "Subject: " . $record->getField('Subject') . "\n";
$headers = array(
"From: filemaker@example.com",
"MIME-Version: 1.0",
"Content-type: text/html"
);
/*
FM helpfully encodes < and >...
*/
$body = preg_replace('/</', '< ', $record->getField('Body'));
$body = preg_replace('/>/', '>', $body);
$rc = mail($record->getField('Recipient'),
$record->getField('Subject'),
$body,
implode("\r\n", $headers)
);
if ($rc) {
$update = $fm->newEditCommand($layout, $record->getRecordId());
$update->setField('Sent_Date', date('m/d/Y'));
$update->setField('Sent_Time', date('H:i'));
$update->setField('Sent_Flag', '1');
$result = $update->execute();
if (FileMaker::isError($result)) {
exit("trouble updating the database after sending email: " .
$result->message . "(" . $result->code . ")");
}
echo "Mailed!\n";
} else {
exit("Mail didn't work.\n");
}
}
