Test PHP Mail Function

When setting up your mail server, you may want to check your php mail function with a simple script.

The PHP Code

The following script was snagged from the php mail() documentation, with a few minor adjustments explained below.
<?php
$to      = 'youremail@yourdomain.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
date_default_timezone_set('America/Chicago');
 
$mail = mail($to, $subject, $message, $headers);
if($mail){
    echo "YES";
} else{
    echo "NO";
}
?>

The Breakdown

While the code is pretty self explanatory, there are a few noteworthy items.

Required Time Zone

If you do not specify a time zone, the mail() function will yell at you. Be sure to specify a time zone through date_default_timezone_set()

Mail Function Boolean Value

The mail() function returns true if mail was successfully sent, and false otherwise. You can use this characteristic to inform the user whether the message was successfully delivered. March 22, 2011
About the Author:

Joseph is the lead developer of Vert Studios Follow Joseph on Twitter: @Joe_Query
Subscribe to the blog: RSS
Visit Joseph's site: joequery.me