为什么在foreach中使用PHP Mailer循环遍历所有收件人将无法正常工作? 我的forearch循环有什么问题?

I'm trying to send an email to each recipient of a list (the recipient is taken from a database query, and the email is sent to all that are "checked", using $_POST['enviar'] in each checkbox to reference each one.

The code does work as intended when using mail(), but it doesn't when I'm using PHPMailer, it just send the email to the first recipient.

So I assume that I'm doing the foreach wrong? How may I correct it?

  if ($correo=mysqli_fetch_array(mysqli_query($conectar,$query))) {
      $total=array();
      $total=count($_POST['enviar']);
      $id = $_POST['enviar'];            
      foreach ($id as $item) {
              include 'private/enviarMails.php'; //PHP Mailer credentials
              $mail->addAddress($item);
              $mail->Subject = $correo['mailAsunto'];
              $mail->Body    = $correo['mailMensaje'];
              if(!$mail->send()) {
                  echo 'El mail no se mandó: ' . $mail->ErrorInfo;
              } else { echo 'Se envió un correo a '.$item;}


      }
  } else { echo 'No se pudieron enviar los correos'; }
      mysqli_close($conectar);  
}

You are including your credentials in every page loop.

Change:

foreach ($id as $item) {
    include 'private/enviarMails.php'; //PHP Mailer credentials
    $mail->addAddress($item);

To:

include 'private/enviarMails.php'; //PHP Mailer credentials
foreach ($id as $item) {
    $mail->addAddress($item);