Login | Contact Us | Site Map | Resources

PHP Functions

Home > PHP Tutorial > PHP Mail Function

PHP Mail Function

The mail() function allows you to send emails, as long as the server has a fully-functional email system already set up.

This function accepts five different parameters, only four of which we will discuss here, and only three of which are required.

Parameter Importance Description
to Required Recipient(s) of Email
subject Required Subject of Email
message Required Message Body of Email
headers Optional From, Reply-To, CC, BCC, Date, Etc.

Listed in order of appearance, the parameters are: mail(to,subject,message,headers)

One of the most simple examples of the mail() function is:

<?php
  mail("an-email@a-domain.com","Brilliant Subject","Boring message body.");
?>

The addition of headers allows you to specify who the email is from and who should be copied and/or blind copied on an email

<?php
  $to = "an-email@a-domain.com";
  $subject = "Why do dogs bury bones in the ground?";
  $message = "Because they can't bury them in trees!";
  $headers = 'From: <an-email@a-domain.com>' . "\r\n";
  $headers .= 'Reply-To: an-email@a-domain.com' . "\r\n";
  $headers .= 'Cc: an-email@a-domain.com' . "\r\n";
  $headers .= 'Bcc: an-email@a-domain.com' . "\r\n";
  mail($to,$subject,$message,$headers);
?>

HTML emails can be sent by specifying the appropriate content-type in the header.

<?php
  $to = "an-email@a-domain.com";
  $subject = "This is an HTML email!";
  $message = "
    <html>
    <body>
    <h2>Cool, right?</h2>
    </body>
    </html>
  ";
  $headers = 'From: <an-email@a-domain.com>' . "\r\n";
  $headers .= "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
  mail($to,$subject,$message,$headers);
?>