Skip to content

Instantly share code, notes, and snippets.

@matteomattei
Last active August 29, 2015 14:03
Show Gist options
  • Save matteomattei/f362f7902a0084934dfb to your computer and use it in GitHub Desktop.
Save matteomattei/f362f7902a0084934dfb to your computer and use it in GitHub Desktop.
How to log email sent from PHP through mail() function
#!/usr/bin/php
<?php
$sendmail = '/usr/sbin/sendmail';
$logfile = '/var/log/mail_php.log';
/* Get email content */
$logline = '';
$mail = '';
$fp = fopen('php://stdin', 'r');
while ($line = fgets($fp))
{
if(preg_match('/^to:/i', $line) || preg_match('/^from:/i', $line))
{
$logline .= trim($line).' ';
}
$mail .= $line;
}
/* Build sendmail command */
$cmd = 'echo ' . escapeshellarg($mail) . ' | '.$sendmail.' -t -i';
for ($i = 1; $i &lt; $_SERVER['argc']; $i++)
{
$cmd .= escapeshellarg($_SERVER['argv'][$i]).' ';
}
/* Log line */
$path = isset($_ENV['PWD']) ? $_ENV['PWD'] : $_SERVER['PWD'];
file_put_contents($logfile, date('Y-m-d H:i:s') . ' ' . $logline .' ==> ' .$path."\n", FILE_APPEND);
/* Call sendmail */
return shell_exec($cmd);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment