How to find php script that sends mail from your linux system

We run into a problem where customers Linux vm was sending a lot of unwanted messages. In order to troubleshoot this problem we did 2 things. Instructions below are for CentOS 6 and 7 but will also work on other distributions with minor configuration changes.
Option 1

1. Check system for open relay with telnet from network that is not on my network list.

telnet "mailsrv" 25
ehlo test.test.com
mail from:test@test.com
rcpt to: myaddress@yahoo.ca "some email address that is not local or in the transport list"

You should get relay denied message. If you did not your system us an open relay and unless it is intended to be one, you need to address this ASAP.

2. If the system is not open relay we need to determine which php script is sending mail.

For this to work php version must be above 5.3
mail.add_x_header = On
mail.log = /var/log/phpmail.log

Now create log file.

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

All done. Now just monitor log file for after you restart apache

service httpd restart 
tail -f /var/log/phpmail.log

Option 2
1. Check the mail queue with command mailq

2. Copy the first column of the mail queue which shows unique mail ID’s – make sure it is one of the spam emails
3. Run the following command

postcat -q ID_OF_MESSAGE

4. Find line starting with “X-PHP-Originating-Script”. This should show which script is generating the spam emails.

After you find the script you can remove it , patch your server and clear your queue.

mailq # view messages in the queue
postsuper -d ALL   # clear the queue