0

I am trying to send email to all the members email id's which is stored in the database. Here is the code

<?php
$sql = mysqli_query($con,"select email from email_list where email");
//$recipients = array();
while($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
    $recipients[]= $row['email'];
}

$to = $recipients;
$repEmail = 'abc@gmail.com';
$subject = "$title";
$body = "$description";
$headers = 'From: xyz <'.$repEmail.'>'. "\r\n"; 
$headers .= 'Reply-To: abc@gmail.com' . "\r\n";
$headers .= 'BCC: ' . implode(', ', $recipients) . "\r\n";

   if (mail($to, $subject, $body, $headers)){
     echo "<script>alert('Email sent')</script>";
    }

    else {
    echo "<script>alert('Email failed')</script>";
    }

?>

In this above code email goes to 1 person.

user3168637
  • 121
  • 4
  • 15
  • The `$to` parameter to [`mail`](https://www.php.net/manual/en/function.mail) is a string, not an array, so I'm surprised it sent anything at all. You need to iterate over the values in your `$recipients` array to send emails to each one of them individually. Note that you'd do better using a package like `Pear` or `PHPMailer` if you want to send lots of emails. – Nick Feb 10 '20 at 07:15

2 Answers2

0

When you look at the pho docs : mail() function

to Receiver, or receivers of the mail. The formatting of this string must comply with » RFC 2822. Some examples are:

user@example.com user@example.com, anotheruser@example.com User User , Another User

It clearly states "to" part should be in rfc2822 compliance. You are passing an array which is not acceptable and thus only first value is taken.

Also it's worth mentioning that:

Note: It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient. For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages

.

Thus I'd suggest you to use some mailing library such as phpMailer or swiftmailer for better functionality or better use mail queue.

Maulik Parmar
  • 617
  • 4
  • 10
0

Your $to should be $to = "address@one.com, address@two.com, address@three.com"

So add

$recipients = array(
  "youremailaddress@yourdomain.com",
  // more emails here
);
$email_to = implode(',', $recipients); // your email address

add $email_to to your $to.