HUBE
HUBE

Reputation: 5

How to send email to Multiple recipients that are in database table?

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 = "[email protected]";
$to = "[email protected]";
$subject = "Online order";
$message = "You just ordered";
$headers = "From:" . $from;
mail($to,$subject,$message, $headers);
?>

Upvotes: 0

Views: 987

Answers (3)

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 = '[email protected]';
$bcc = implode(',', $recipients);
$headers .= 'From: [email protected]\r\n'; //here you can set sent from
$headers .= 'BCC: '.$bcc. '\r\n'; 
mail($to,$subject,$message, $headers);

Upvotes: 0

am tech science
am tech science

Reputation: 11

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);}}

Upvotes: 1

Rahul
Rahul

Reputation: 18577

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

Upvotes: 2

Related Questions