Skip to main content

Record of Resolving the Issue of Failing to Send Emails via SMTP on CentOS

· 2 min read
zenge
Software Rookie @ China

Background

A LAMP application deployed on CentOS.

March 30, 2012

The day before yesterday, a bug was discovered during testing: the 64-bit CentOS system was unable to send activation emails for user registration.

centos smtp

Logged into the server and printed the log, which recorded the error_msg as permission deny.

After debugging and searching online for half a day, no relevant results were found.

The main reasons mentioned online were that fsockopen might be disabled, and suggested using pfsockopen or stream_socket_client as alternatives.

I tried all these methods, but none of them worked.

Since calling these functions on Windows had no issues and emails could be sent successfully, I wondered if it might be a Linux system issue. It turned out to be the CentOS firewall.

In fact, I had been troubled by SELinux several times before, so in the future, when encountering problems, I should first consider if SELinux is the culprit.

Since SELinux is enabled by default, it must have its benefits. The server cannot disable SELinux, so I searched these words online: selinux+smtp.

Finally, I found the answer: SELinux indeed prevents HTTP from connecting to the network.

I tried executing the following command:

    setsebool -P httpd_can_network_connect=1

Sure enough, emails could be sent immediately. It seems I need to properly study SELinux.

Reference Details

https://www.vbulletin.com/forum/showthread.php/217997-smtp-mail-and-SElinux-in-enforcing-mode

To allow PHP/Apache to connect to port 25, issue the following commands as root: setsebool -P httpd_can_network_connect=1

To allow PHP mail() to work, issue the following command as root: setsebool -P httpd_can_sendmail=1

April 19, 2012

Today, I encountered the issue of the server failing to send emails again. The server had been moved from local hosting to a telecom data center.

The error appeared again: SMTP Error: Could not connect to SMTP host.

After searching for a long time without finding the cause, I resorted to the ultimate solution: reboot.

After restarting httpd, the problem disappeared. It’s really bizarre. Logically, the server was shut down yesterday and only powered on at the new data center, so httpd should have already been restarted.

For now, I’ll note down this issue. Restarting httpd is not a good solution.