ssmtp_wrapper.php
#!/usr/local/bin/php
<?php
// Set up the default config values.
'message_path' => '/var/log/sendmail_php.log',
'error_path' => '/var/log/sendmail_php.error',
'parse' => FALSE,
'ignore_dots' => FALSE,
);
// Allow the config file to overwrite the defaults.
if (file_exists($config_path = '/usr/local/etc/sendmail.conf.php')) { require_once($config_path);
} else {
$options = $defaults;
}
define('MESSAGE_PATH', $options['message_path']); define('ERROR_PATH', $options['error_path']);
// Helper function for logging
function log_message($message, $message_type = 'message') {
if ($message_log_file === NULL)
$message_log_file = fopen(MESSAGE_PATH
, 'a');
if ($error_log_file === NULL)
$error_log_file = fopen(ERROR_PATH
, 'a');
if ($message_type == 'message')
fwrite($message_log_file, date('[d/m/Y H:i:s] ').$message."\n"); else
fwrite($error_log_file, date('[d/m/Y H:i:s] ').$message."\n"); }
// Initialise these to false so we know if they got set.
$from = $to = FALSE;
// Scan the command-line arguments.
foreach ($_SERVER['argv'] as $index => $argv) {
if ((bool) $argv AND $argv[0] == '-') {
switch ($argv[1]) {
case 'f':
break;
case 't':
$options['parse'] = TRUE;
break;
case 'i':
$options['ignore_dots'] = TRUE;
break;
case 'o':
if ($argv[2] == 'i')
$options['ignore_dots'] = TRUE;
break;
}
} else {
$to = $argv; // Always assign $to so it's the last non-hyphenated param.
}
log_message("Index: $index, Arg: $argv");
}
// Check that valid options were passed.
if (! (bool) $to AND ! (bool) $options['parse']) {
log_message($msg = 'Error: Please specify a to address on the command line, or use -t', 'error');
}
// More valid checks.
if (! (bool) $options['ignore_dots']) {
log_message($msg = 'This wrapper only supports operation in -i mode (ignore single dots on a line).', 'error');
}
// Read in the message from stdin.
$stdin = '';
while ((bool
) ($buffer = fread(STDIN
, 1024))) $stdin .= $buffer;
// Log the contents of stdin.
log_message("STDIN: $stdin");
// Should we try to parse the "to" and "from" parts of our message?
if ($options['parse'] === TRUE) {
foreach ($lines as $line) {
if (substr($line, 0, 4) == 'To: ') { if ((bool) $temp_to)
$to = $temp_to;
} elseif (substr($line, 0, 6) == 'From: ') { $temp_from = substr($line, 6); if ((bool) $temp_from)
$from = $temp_from;
}
}
log_message("Parsed \$to: $to, \$from: $from");
}
// Ensure we don't have bad chars.
// Now try to pass it to sSMTP.
$descriptor_spec = array( 0 => array('pipe', 'r'), // Child process will read; We shall write! 1 => array('pipe', 'w'), // Backwards, eh? Check the PHP docs. 2 => array('file', ERROR_PATH
, 'a'), );
$command = '/usr/sbin/sendmail -i -f'.$from.' '.$to;
log_message("\$command: $command");
$sendmail = proc_open($command, $descriptor_spec, $pipes);
$sendmail_stdin = $pipes[0];
$sendmail_stdout = $pipes[1];
fwrite($sendmail_stdin, $stdin);
$result = stream_get_contents($sendmail_stdout);
} else {
log_message('Unable to execute!', 'error');
$return_value = 255;
}