27

I know there are a few similar questions to this but I just can't get it working.

Ok, I have a list of emails grabbed from my database in a variable called $emailList. I can get my code to send an email from a form if I put the variable in the $to section but I cannot get it to work with bcc. I've even added an email to the $to incase it was that but it doesn't make a difference.

Here is my code.

$to = "name@mydomain.com";
$subject .= "".$emailSubject."";
$headers .= 'Bcc: $emailList';
$headers = "From: no-reply@thepartyfinder.co.uk\r\n" . "X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';

if (mail($to, $subject, $message, $headers)) {
    $sent = "Your email was sent!";
} else {
    $sent = ("Error sending email.");
}

I've tried both codes:

$headers .= 'Bcc: $emailList';

and

$headers .= 'Bcc: '.$emailList.';

It's not that the emails aren't separated because they are. I know they are because it works if I put $emailList in the $to section.


I Should add, ignore the $message bits and the HTML stuff. I've not provided all of that so that is why it's missing from this code.

A.L
  • 10,259
  • 10
  • 67
  • 98
glln
  • 533
  • 1
  • 6
  • 16

2 Answers2

61

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: no-reply@thepartyfinder.co.uk\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
gregheo
  • 4,182
  • 2
  • 23
  • 22
  • I've never had an issue when not specifying 'To' in the headers. – Bot Mar 01 '12 at 22:53
  • 4
    I don't doubt it. I just mean there are a variety of mail servers and spam filters out there and emails with missing/strange header bits generally get higher spam scores. – gregheo Mar 01 '12 at 22:57
13

You were setting BCC but then overwriting the variable with the FROM

$to = "name@mydomain.com";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: no-reply@thepartyfinder.co.uk\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }
Bot
  • 11,868
  • 11
  • 75
  • 131
  • 2
    The `\r\n` should be in double quotes otherwise it is taken literally. Only the one on the `BCC` had this problem. – drew010 Mar 01 '12 at 22:56