Otto Otto - 2 months ago 9
PHP Question

PHPMailer: Send emails to multiple recipients error

As in the title, I can't send an email to multiple recipients because I retrieve the following error:


Message could not be sent. Mailer Error: You must provide at least one recipient email address.


I'm using this code:

$stmt=$db->prepare("select email from app_users where enabled=1");
if (!$stmt) {
log_msg($db->error);
die();
}
if (!test_execute($stmt->execute())) die("ERROR");
$emailto=fetchArray2($stmt);
$stmt->close();
foreach ($emailto as $contacts) {
$mail->AddAddress($contacts);
}


What's wrong?

print_r($emailto);

Array
(
[0] => Array
(
[email] => recipient1@hotmail.com
)

[1] => Array
(
[email] => recipient2@gmail.com
)

[2] => Array
(
[email] => recipient3@yahoo.com
)


)

Answer

@Natrium nearly had it. You're not accessing your array elements correctly. Do it like this:

foreach ($emailto as $contacts) {
  $mail->addAddress($contacts['email']);
}

It's also a good idea to check return values, perhaps:

foreach ($emailto as $contacts) {
  if (!$mail->addAddress($contacts['email'])) {
    echo 'Address rejected: '.$contacts['email'];
  }
}
Comments