Most websites and CMS’s need to send email messages, this happens mainly through PHP’s mail() function. With this function you can easily compose email messages using various scripts. There is one problem though: If your website or CMS gets hacked, it’s very easy for the hackers to abuse this function and send tens of thousands of messages using your server. To combat this, you’ll a need a way to figure out what the mail() function is doing and what scripts are using it. This can be done bij enabling the mail.log and mail.add_x_header options in your php.ini configuration. These two options will make PHP log every attempt by a script to send email.

To set this up, we’ll need to create the log file first. Log in to your server using SSH and execute the following commands:

touch /var/log/phpmail.log
chown apache:apache /var/log/phpmail.log
chmod 600 /var/log/phpmail.log

In the example above I made the user ‘apache’ owner of the logfile, this could also be www-data or some other user depending on your Apache configuration. The apache2.conf file in /etc/apache2/ will tell you under what user Apache runs.

Now that we’ve created the log files, it’s time to edit php.ini. Add or edit the following lines in your php.ini file. This file is almost always located in /etc

mail.add_x_header = On
mail.log = /var/log/phpmail.log

After these lines are set, reload apache and you’re done. From now on Apache will add a line like this every time mail() sends an email message:

Mar 1 17:15:29 mail() on [/var/www/vhosts/]: — Headers: MIME-Version: 1.0 X-Mailer: osCommerce Mailer

As you can see, emailscript.php on line 12 send an email to on March 1st 17:15:19

If your server is sending huge amounts of email messages it might be wise to setup log rotate. Otherwise the phpmail.log file will get huge. You can do this by adding a file to the /etc/logrotate.d/ directory. Here’s an example:

/var/log/phpmail.log {
    rotate 4
	create 0640 apache apache