PHP “mail()” function sends mail from php5 cli but not when the script is run by a browser

荒凉一梦 提交于 2019-12-24 00:32:01

问题


I have configured my server to send mail by setting "sendmail_path = "/usr/sbin/sendmail" in "/etc/php5/apache2/php.ini" and sendmail is installed on the server.

When I run this script, or any variation of it, from php5 via the cli the mail sends just fine, but when I have a browser run it, i.e. Chrome or Firefox, it fails everytime.

<?php
 $to = "notreal@email.com";
 $subject = "Hi!";
 $body = "Hi,\n\nHow are you?";
 if (mail($to, $subject, $body)) {
   echo("<p>Message successfully sent!</p>");
  } else {
   echo("<p>Message delivery failed...</p>");
  }
?>

I am using the "php5-cli" package for a command line interpreter.

Other PHP based web-apps that rely on the PHP "mail()" function don't send mail either.


回答1:


Apache and the CLI seem to use different configurations in your setup.

Compare the configuration in /etc/php5/cli/php.ini with your Apache's php.ini. Probably something is not working with the sendmail configuration for Apache's PHP and the CLI configuration is right.




回答2:


You first need to verify that current setting is the one you think it is:

var_dump(ini_get('sendmail_path'));

If it's different in web and CLI, PHP is probably different php.ini files. Run this:

phpinfo(INFO_GENERAL);

... and find this part (your values will differ from mine):

Configuration File (php.ini) Path => C:\Windows
Loaded Configuration File => C:\Program Files\PHP\php.ini
Scan this dir for additional .ini files => (none)
Additional .ini files parsed => (none)

That will help you identify the php.ini file you need to edit.

(Whatever, it's weird that this comes misconfigured in a Linux server.)




回答3:


When you run php from cli it runs under account you logged in to linux. When you run from Apache php runs as user that Apache runs under, usually 'nobody'

There could be several reasons why mail from 'nobody' fails - some spam filters will reject it.

Also I'm not sure what you mean by 'fails' - simply not receiving an email that you expect does not mean it wasn't sent. You should examine your mail log, usually in /var/log/maillog and just after running your script from the browser check the latest few lines in that log, type

# tail -20 /var/log/maillog

and see if you can spot your email being either sent or rejected. Also wait a couple minutes and check that log again - your original email may come back as bounced from some mail server, it will include explanation of why it was bounced



来源:https://stackoverflow.com/questions/8608249/php-mail-function-sends-mail-from-php5-cli-but-not-when-the-script-is-run-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!