How does php mail() work?

php has a powerful function called mail(). You can use this function to send emails from your script.

// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

// send email
echo mail("","My subject",$msg);

Under the windows/xampp environment, the script runs successfully and print “1” on the screen. But you can not find the email by checking the email box Checking php.ini, I found the following configuration line:


It means php will execute the program mailtodisk.exe to handle the email. The program, however, just writes the email to a file on disk(in our case, the file is in the folder c:\xampp\mailoutput\). If you comment the configuration line and restart apache, you will get the following error when running the script:

Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing in xxx

You can un-comment the “sendmail_from=” configuration line in php.ini, but you still get the error:

Warning: mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in xxx

This is because if you do not specify a mailer program inĀ  php.ini, php mail function will try to connect to a SMTP server to deliver the mail itself. However, I have not set up a SMTP server on my computer so the mail function fails.

xampp comes with a fake sendmail program under the installation directory:c:\xampp\sendmail\. You can specify it as the mailer program in php.ini. But this fake sendmail needs a real smtp server set in its own configuration fileĀ sendmail.ini. Otherwise, although the php mail() succeeds, the email is not actually sent.

So if you use php mail() in Windows, you must specify a real smtp server to make the function work.

On Linux, the php mail function seems always successful(return 1). This is because the sendmail_path parameter in php.ini is set to “/usr/sbin/sendmail -t -i”(on my CentOS) . The sendmail program is almost accompanied by every release of Linux. Even there is no mail server listening on your machine, the sendmail command can be executed without a problem. But that does not mean the email is sent to the recipient successfully. If the mail server is not running at the moment the php mail function is called, the email would be saved in a queue of the mail server. When the mail server starts sometime later, the email will be delivered then.

Posted in

Comments are closed, but trackbacks and pingbacks are open.