Apple Bux
Apple Bux

Reputation: 95

PHP Mailer Mails getting repeated for every user I send mails to

I have this code for sending mails using PHPMailer. The problem is that mails are getting repeated with my current code. It goes in this format.

Mail Sends To:

[email protected] (1st go)
[email protected], [email protected] (2nd go)
[email protected], [email protected], [email protected] (3rd go)
[email protected], [email protected], [email protected], [email protected] (4th go)

....and so on.

I think this is because of my while loop logic. What can be the other way to send bulk email to members in my database just once without getting repeated?

Here is my code:

$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = $mainf['set_smtp_host'];
$mail->Port = $mainf['set_smtp_port'];
$mail->SMTPSecure = $mainf['set_smtp_security'];
$mail->IsHTML(true);
$mail->SMTPAuth = true;
$mail->Username = $mainf['set_smtp_uname'];
$mail->Password = $mainf['set_smtp_pass'];
$mail->setFrom($mainf['set_noreply_email'], $mainf['set_site_name']);
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->Subject = $sub;
$mail->Body    = $mail_msg;

$emails = $pdo->prepare("SELECT mem_name, mem_email FROM members WHERE mem_email_verified = 'yes' ORDER BY mem_id ASC LIMIT 5");
$emails-> execute();

while($u = $emails->fetch()){
  $mail->addAddress($u['mem_email'], $u['mem_name']);
  $send = $mail->Send();
}

if($send){
  $msg = "<div class='alert alert-success'>Mail sent to all members successfully.</div>";
}else{
  $msg = "<div class='alert alert-danger'>Mail Server Error! Please refresh the page and try again.</div>";
}

Also, in the mailbox I can see who are the others to whom the mail was sent to. Can I add BCC option to send bulk emails just once without getting it repeated for anyone?

Upvotes: 2

Views: 52

Answers (1)

Amrit Shrestha
Amrit Shrestha

Reputation: 1660

// option 1
while($u = $emails->fetch()){
  $mail->addAddress($u['mem_email'], $u['mem_name']);
  $send = $mail->Send();
  $mail->ClearAllRecipients(); // reset the `To:` list to empty

}

// option 2
while($u = $emails->fetch()){
  $mail->addAddress($u['mem_email'], $u['mem_name']);
  $mail->AddBCC($u[0]);
}

$mail->send();

Upvotes: 3

Related Questions