首页 > 解决方案 > 我向其发送邮件的每个用户都会重复 PHP Mailer 邮件

问题描述

我有使用 PHPMailer 发送邮件的代码。问题是我当前的代码重复了邮件。它采用这种格式。

邮件发送至:

user@gmail.com (1st go)
user1@gmail.com, user@gmail.com (2nd go)
user2@gmail.com, user1@gmail.com, user@gmail.com (3rd go)
user3@gmail.com, user2@gmail.com, user1@gmail.com, user@gmail.com (4th go)

....等等。

我认为这是因为我的 while 循环逻辑。还有什么其他方法可以向我的数据库中的成员发送一次批量电子邮件而不会重复?

这是我的代码:

$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>";
}

此外,在邮箱中,我可以看到邮件被发送到的其他人是谁。我可以添加密件抄送选项以仅发送一次批量电子邮件而无需为任何人重复发送吗?

标签: phpemailphpmailer

解决方案


// 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();

推荐阅读