Rosamunda Rosamunda - 4 months ago 23
PHP Question

Why using PHP Mailer inside a foreach to loop through all recipients won't work? What's wrong with my forearch loop?

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

Answer

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