PHP Sending Email Sending Email - The basics, more details, and a full example

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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:

  • the From name and email address the user will see
  • the Reply-To email address the user's response will be sent to
  • additional non-standards headers like X-Mailer which can tell the recipient this email was sent via PHP
$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);

NOTE: Although mail() may return TRUE, it does not mean the email was sent or that the email will be received by the recipient. It only indicates the mail was successfully handed over to your system's mail system successfully.

If you wish to send an HTML email, there isn't a lot more work you need to do. You need to:

  1. Add the MIME-Version header
  2. Add the Content-Type header
  3. Make sure your email content is HTML
$to      = '[email protected]';                            
$subject = 'Email Subject';                                     
$message = '<html><body>This is the email message body</body></html>';       
$headers = implode("\r\n", [
    'From: John Conde <[email protected]>',
    'Reply-To: [email protected]',
    'MIME-Version: 1.0',
    'Content-Type: text/html; charset=ISO-8859-1',
    'X-Mailer: PHP/' . PHP_VERSION
]);

Here's a full example of using PHP's mail() function

<?php

// Debugging tools. Only turn these on in your development environment.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

// Special mail settings that can make mail less likely to be considered spam
// and offers logging in case of technical difficulties.

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

// The components of our email

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

// Send the email

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

// Check the results and react accordingly

if ($result) {
  
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
  
}
else {
  
    // Your mail was not sent. Check your logs to see if
    // the reason was reported there for you.
  
}

See Also

Official documentation

Related Stack Overflow Questions

Alternative Mailers

Email Servers

Related Topics



Got any PHP Question?