PHP Unable to send email from web application .. (but commandline works)

This issue seems to have popped up a couple times over the past couple weeks so I figure I would capture the resolution here in the event someone stumbles onto this post and it's able to help them. Security is rarely convenient and this is an example of that.

Symptom:

CentOS machine running current on patches and running a current version of PHP, let's say PHP 5.3 or higher. PHP script is able to sent email from the command line, but when trying to send an email with PHP through the web browser it fails. Actually it doesn't "fail" it just doesn't seem to ever send.

Resolution:

SELinux is running on the machine and is preventing the Apache process to send out emails. There are a couple approaches you can take for this. To quickly test and confirm that the problem is in fact SELinux, and not something else, you can temporarily disable SELinux.

  • First verify SELinux is running with the command (as root) getenforce
  • Next, if SELinux is running you can disable with the command, again as root, setenforce Permissive

 

SELinux with be disable until you reboot the machine or enable it with setenforce Enforcing. You can permanently disable SELinux is you so desire editing the file /etc/sysconfig/selinux and changing the setting SELINUX=

Test your PHP Mail functionality now from the web application. If it works then you need to have SELinux allow the apache process to send emails. In order to do this, run the commands

  • setsebool -P httpd_can_sendmail 1
  • setsebool -P httpd_can_network_connect 1

 

You should now be able to re-enable SELinux and successfully send emails from your application in the browser.