0

I have the below code. I usually send an email to one recipient. My question is how can I modify for it to send to multiple recipients that are in my database.

Suppose I have a table called "tblemails" and a column called "email".

Note:

I also dont want to show all address to each member of my list (something like using Bcc).

Please Help?

<?php
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
$from = "sender@gmail.com";
$to = "receiver@gmail.com";
$subject = "Online order";
$message = "You just ordered";
$headers = "From:" . $from;
mail($to,$subject,$message, $headers);
?>
Strawberry
  • 33,750
  • 13
  • 40
  • 57
HUBE
  • 3
  • 2
  • I assume (going by the e-mail subject) each e-mail is going to be different, so use a loop. Or if you're going to be sending a lot of e-mails, perhaps use a bulk mail service. – Jonnix Aug 27 '19 at 11:12
  • You can't using the simple php native approach. Instead you need to use a smtp client implementation. Using that you can name as many recipients as you like (and as that smtp server you are using allows). – arkascha Aug 27 '19 at 11:12

3 Answers3

2

I am sure you can fetch the email data from the database,

You can update header string as

$headers .= 'BCC: '. implode(",", $emailData) . "\r\n";

$emailData - Should be 1-D array which should contains all email ids. ref

Rahul
  • 18,271
  • 7
  • 41
  • 60
1

you can use while loop

$a = mysqli_query($con,"SELECT email FROM table");
while($row = mysqli_fetch_array($a)){$email = $row['email'];mail($email,$subject,$msg,$header);}}
0

I hope you know how to fetch the email ids from the database.

$link = mysqli_connect("localhost", "root", "password", "DBName"); 

$sql = "SELECT * FROM tableA"; 
if ($res = mysqli_query($link, $sql)) { 
   if (mysqli_num_rows($res) > 0) { 
      while ($row = mysqli_fetch_array($res)) { 
         $recipients[] = $row['email'];
      }
   }
}

$to = 'some@email.com';
$bcc = implode(',', $recipients);
$headers .= 'From: noreply@company.com\r\n'; //here you can set sent from
$headers .= 'BCC: '.$bcc. '\r\n'; 
mail($to,$subject,$message, $headers);