A typical email has three main components:

  1. A recipient (represented as an email address)
  2. A subject
  3. A message body

Sending mail in PHP can be as simple as calling the built-in function mail(). mail() takes up to five parameters but the first three are all that is required to send an email (although the four parameters is commonly used as will be demonstrated below). The first three parameters are:

  1. The recipient’s email address (string)
  2. The email’s subject (string)
  3. The body of the email (string) (e.g. the content of the email)

A minimal example would resemble the following code:

mail('[email protected]', 'Email Subject', 'This is the email message body');

The simple example above works well in limited circumstances such as hardcoding an email alert for an internal system. However, it is common to place the data passed as the parameters for mail() in variables to make the code cleaner and easier to manage (for example, dynamically building an email from a form submission).

Additionally, mail() accepts a fourth parameter which allows you to have additional mail headers sent with your email. These headers can allow you to set:

$to      = '[email protected]';             // Could also be $to      = $_POST['recipient'];  
$subject = 'Email Subject';                     // Could also be $subject = $_POST['subject'];  
$message = 'This is the email message body';    // Could also be $message = $_POST['message'];  
$headers = implode("\\r\\n", [
    'From: John Conde <[email protected]>',
    'Reply-To: [email protected]',
    'X-Mailer: PHP/' . PHP_VERSION
]);

The optional fifth parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail/postfix with the -f sendmail option.

$fifth  = '[email protected]';

Although using mail() can be pretty reliable, it is by no means guaranteed that an email will be sent when mail() is called. To see if there is a potential error when sending your email, you should capture the return value from mail(). TRUE will be returned if the mail was successfully accepted for delivery. Otherwise, you will receive FALSE.

$result = mail($to, $subject, $message, $headers, $fifth);