Search code examples
phpemailhtml-emailemail-headers

mail() from php.net manual: difference between "to" and "to-header"


In the php.net example for mail(), two different addresses are used for $to and the additional header information "To: ...":

<?php
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

$subject = 'Birthday Reminders for August';

// message
$message = '<html> ... </html>';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?>

So my question is: you need to provide $to for the syntax of mail(), however you cannot use the format Name <email@domain.com>, this you can only do in the additional header information, right?

So first, why does the example on php.net send the mail to 4 different people (because they use different e-mail addresses for $to and for the header information), this really irritates me!?

And secondly, if I want to send the mail to only 1 person (and only 1 time) and I want to use the format Name <email@domain.com>, how should I do that? Use it in $to as well as the header information? Will the person then receive the e-mail twice?


Solution

  • Recommend you to use PHP Mailer class instead of internal mail() function. There are several reasons to use PHP Mailer:

    • the ability to use your own smtp
    • better chance to get not be listed at spam (main reason)
    • easy to use