10.09.07

How to make PHP mail () function work on Windows

Posted in Programming at by chenty

mail() is a useful and powerful function in PHP, but many developers got problems to make mail() work properly on Windows. Many these problems were related to headers and different line feed formats between Windows and Linux. However, this post does not address these problems. The problem I encountered last week was how to make mail() function to send even the simplest mail on Windows.

The server setup:
Windows Server 2003 Standard Edition (SP2)
Apache 2.2
PHP 5.2.4
MySQL 5.1

run a test script with phpinfo() to confirm the server settings. There were several lines that relate to mail():
smtp = localhost
smtp_port = 25
sendmail_from = yourname@yourdomain.com
sendmail_path =

Windows and Linux handle mail() differently. Linux uses “sendmail” whereas Windows employs SMTP. You can refer to PHP manual for more information:
http://ca3.php.net/function.mail

In this post, I will only cover Windows. Windows Server 2003 comes with IIS 6.0, which supports SMTP. If you are a .NET programmer, you will find mail features working out of box. Unfortunately, this was not the case for PHP. You can try to run the following script to check if mail() works:

  1. if(mail(‘test@test.com’,‘test subject’,‘test message’))
  2. {
  3.   echo(‘ok’);
  4. }
  5. else
  6. {
  7.   echo(‘not ok’);
  8. }

If the script returns ‘not ok’ when you run the code, that means mail() function could not send the mail through SMTP. So what was the problem? A good way to demonstrate the problem is run an email client (e.g. Outlook Express) and setup a new account using “localhost” as SMTP. When you try to send a new message, you will receive an error similar to this one:

Server Response: ‘550 5.7.1 Unable to relay for yourname@yourdomain.com’, Port: 25, Secure(SSL): No, Server Error: 5500

This is the reason your PHP script cannot send the mail: by default, IIS restricts all SMTP relay! In order to solve the problems, you need to grant access to your server IP:
1. Open “IIS Manager”;
2. Right click “Default SMTP Virtual Server” and select “Properties”;
3. In “Access” Tab, click “Relay…”;
4. Check “only the list below” and click “Add” to add the server IP.

Now, if you open Outlook Express and create a new message, the mail will be sent out properly. Now, run the test script I wrote above, the script should return ‘ok’ and you should receive the mail in your mailbox amazingly!

Leave a Comment