Send Email with PHP

Sending email messages is a common task for web applications. You can use the built-in PHP mail() function to dynamically create and send email messages to one or more recipients.

The mail() function is a part of the PHP core but to use it you must have a mail server setup on your domain. Mail servers are pretty standard at most hosting services.

// Define the email addresses to send this message to.
$toEmails = array(
    'John Doe <johnd@somedomain.com>',
    'anothername@someotherdomain.com'
);

// Define the email address this message is coming from.
$fromEmail = 'My Service <myservice@mydomain.com>';

// Define the email address to send replies to.
$replyEmail = 'My Service <myservice@mydomain.com>';

// Define the subject of the email.
$subject = 'The Subject Line of My Email';

// Define the email content.
$message =
'<html><body>
    <h1 style="color:#cccccc;">Hello</h1>
    <p style="color:#000000;font-size:18px;">What\'s up!</p>
</body></html>';

// Make sure each 'message' line doesn't exceed 70 characters.
$message = wordwrap($message, 70);

// Begin the headers
$headers = 'MIME-Version: 1.0' . "\r\n";

// To send HTML formatted mail, the Content-Type header must be set to 'text/html'.
$headers .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";

// For plain-text emails, the Content-Type header must be set to 'text/plain'.
// $headers .= 'Content-Type: text/plain; charset=utf-8' . "\r\n";

// Construct the email headers.
$headers .=
    'From: ' . $fromEmail . "\r\n" .
    'Reply-To: ' . $replyEmail . "\r\n" .
    'X-Mailer: PHP/' . phpversion()
;

// Loop over each recipient and send them an email.
$counter = 0;
foreach( $toEmails as $email )
{
    // If the send was successful, increment the counter.
    if( mail( $email, $subject, $message, $headers) )
    {
        $counter++;
    }
}

// Output the status of the script.
echo ' emails have been sent.'

Notes

  • You can set the default mail server in the php.ini file with the SMTP setting. This setting can be temporarily set in-script with the ini_set() function.
  • No support for SMTP authentication.

There are extensions that provide the missing features in mail().