We help IT Professionals succeed at work.

Syntax of PHP html mail header

lepirtle asked
I am trying to place a form variable into a PHP HTML mail header script.

I know the script works if I hard code an email address but when I try to insert an email address that has been passed to the script using a form variable I cannot make the variable output the contents of the variable.

In the attached code, the variable I am trying to place is $_POST['email']. Placing this variable in the message body works just fine outputting the contents of the variable. But when I try to place that variable in the header line that reads
$headers .= 'Cc: $_POST['email']' . "\r\n";
The contents of the variable will not output. I have tried every combination of single apostrophes, double apostrophes, etc but cannot come up with the proper syntax.

Might someone steer me in the right direction?
// multiple recipients
$to  = 'me@mydomaine.com' . ', '; // note the comma
$to .= 'you@your.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
  <title>Birthday Reminders for August</title>
  <p>Here are the birthdays upcoming in August! '.$_POST['email’].'</p>

// 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: Lee <me@mydomain.com>, john <johnr@john.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <someplace@example.com>' . "\r\n";
$headers .= 'Cc: $_POST['email']' . "\r\n";
$headers .= 'Bcc: tgifl@domain.com' . "\r\n";

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

Open in new window

Watch Question

what I learned was single quotes don't evaluate the body.  use double quotes when you want to process variables.  But even better is to be explicit and concatenate variables instead:

$headers .= 'CC: ' . $_POST['email'] . "\r\n";

That will always work.  That is, if $_POST['email'] has a value, and you can print it to log and see it, that should properly merge into the output string.


Thanks so much. That worked perfectly!
I appreciate your quick and accurate solution.
Obviously I am just learning PHP and this will help advance my progress no that learning curve.