Sep 17

url referer : – http://www.howtoforge.com/how-to-log-emails-sent-with-phps-mail-function-to-detect-form-spam

After sometimes it occur to me that me how to get log of mail that was sent from formmail on my web because i always wonderring who sent the email is it spam or not, then i found this artickel http://www.howtoforge.com/how-to-log-emails-sent-with-phps-mail-function-to-detect-form-spam 🙂

Okay let’s start the installation

1. Installing the Log  script

Create new file /usr/local/bin/phpsendmail

vi /usr/local/bin/phpsendmail

Then paste this

#!/usr/bin/php

<?php

$sendmail_bin = ‘/usr/sbin/sendmail.postfix’; // i use postfix and postfix sendmail bin was located on /usr/sbin/sendmail.postfix , it depend on your mail system

$logfile = ‘/var/log/mail.form’;

//* Get the email content

$logline = ”;

while ($line = fgets(STDIN)) {

if(stristr($line,’to:’) || stristr($line,’from:’)) $logline .= trim($line).’ ‘;

$mail .= $line;

}

//* compose the sendmail command

$command = ‘echo “‘.$mail.'” | ‘.$sendmail_bin.’ -t’;

for ($i = 1; $i < $_SERVER[‘argc’]; $i++) {

$command .= $_SERVER[‘argv’][$i].’ ‘;

}

//* rotate log if it gets too big

if(is_file($logfile) && filesize($logfile) > 10000000) {

if(is_file($logfile.’.old’)) unlink($logfile.’.old’);

exec(‘cp -pf ‘.$logfile.’ ‘.$logfile.’.old’);

exec(‘cat /dev/null > ‘.$logfile);

}

//* Write the log

system(‘echo “‘.date(“Y-m-d H:i:s”).’ ‘.$_ENV[‘PWD’].’ ‘.$logline.'” >> ‘.$logfile);

//* Execute the command

return shell_exec($command);

?>

Now make the script executable…

chmod +x /usr/local/bin/phpsendmail

… and create the logfile and make it writable:

touch /var/log/mail.form
chmod 777 /var/log/mail.form

2. Modifying the main.cf

Again it depend on your mail system , on my ssystem i use postfix to send the email from my formmail, in other system usually the email send from sendmail or from the php itself in that case you need to edit php.ini. In my system i need to modify postfix main.cf

go to your main.cf on /etc/postfix/main.cf and changes this

vi /etc/postfix/main.cf

sendmail_path = /usr/local/bin/phpsendmail

then relaod your postfix

# /etc/init.d/postfix reload

3 Test the setup

To test this setup, create a new php file with the name mailtest.php in one of your websites with the content:

<?php
mail('yourname@yourdomain.com','This is a test message subject','This is a test message body');
echo 'Mail sent.'; 
?>
to see the log  you can use
# tail /var/log/mail.form -f
2009-09-17 15:49:30 /home/test/public_html To: test@yahoo.com From: test <test@yahoo.com> 
2009-09-17 16:12:01 /home/test/public_html To: test2@bi.edu From: test <test2@bi.edu>