Home >Backend Development >PHP Tutorial >Why PHP cannot send emails using mail function

Why PHP cannot send emails using mail function

WBOY
WBOYOriginal
2016-07-29 09:03:38920browse

[Introduction]PHP requires an installed and running mail system in order to make the mail function mail() available. The mail system program used is set in the php.ini file.

Use the following code to send emails, but the delivery always fails.


[php] view plaincopyprint?
01.02.$to = "xxxxxxxx@qq.com";
03.$subject = "Test mail";
04.$message = "Hello! This is a simple email message.";
05.mail($to,$subject,$message);
06.?>
After checking, PHP requires an installed and running mail system in order to use the mail function mail() is available. The mail system program used is set in the php.ini file. The specific solutions are as follows:
1. Install sendmail
sudo apt-get install sendmail
sudo apt-get install sendmail-cf
sudo apt-get install mailutils
2. Configure sendmail
Open /etc/mail/sendmail.mc and find The following line:
DAEMON_OPTIONS('Family=inet, Name=MTA-v4, Port=smtp, Addr=127.0.0.1')dnl
Change 127.0.0.1 to 0.0.0.0
Execute the following command to back up the old configuration file and generate New configuration file:
cd /etc/mail
mv sendmail.cf sendmail.cf~
m4 sendmail.mc > sendmail.cf
3. Test
echo "This is a test mail." | mail -s "test "xxxxxxxx@qq.com
Note: This email will be received as spam. In addition, if you use the 163 mailbox, it may be directly filtered and cannot be received.
4. Configure the php.ini file
Open /etc/php5/apache2/php.ini and find the following line:
; sendmail_path =
Change the line to: sendmail_path = /usr/sbin/sendmail -t

This is special It should be noted that the "-t" parameter is essential. If it is missing, the mail() function will fail to execute when the original php file is executed through the browser. However, if the original php file is executed directly on the server using the php command line There will be no problem.

5. Restart apache
sudo /etc/init.d/apache2 restart


At this point, execute the original php code again, and the email is sent successfully.


The above introduces the reason why PHP cannot use the mail function to send emails, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn