Sending Mail safely

Summary PHP's mail() function is exploitable for sending Spam, when insufficient argument checking is performed.
Solution: replace all calls to mail() through the SafeMail interface.
Note that regular form validation should be done beforehand, see Contact Forms.

Example

// Load the SafeMail feature (the 4 in SafeMail4 marks the file as PHP4 code rather than PHP5)
require_once "SafeMail4.class.php";

// For each message to send, create a SafeMail object and set all the parameters.
$message = new SafeMail();
$message->set_subject($_REQUEST['subject']);

// Send message to Gisela (or other hard coded recipient)
$message->add_recipient("gisela@spallek.com");

// Send message to all recipients given from the form.
// Warning: recipients given from the form must be checked.
// Use a whitelist and allow only recipients from this list.
$message->whitelist(file_get_contents("path/to/whitelist.txt")); // file contains one valid recipient per line
$message->add_recipient_check_whitelist(explode(",", $_REQUEST['to'])); // accepts only whitelisted recipients

// Set sender address; if no address is given or the address is invalid, use a hard coded (secure) sender address.
if (! $message->set_from($_REQUEST['from']))
    $message->set_from("gisela@spallek.com");

// Set the message Body
$message->set_body("message text");

// Send the message
$message->send();

Notes

Files