PHP“mail()”函数从php5 cli发送邮件,但不是在浏览器运行脚本时发送邮件

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,

How 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.

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.

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.)

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