Reputation: 391
I am trying to run the emails to 10 different users, i have made variable $friendsEmails into an array which contains 10 different emails, however looks that it will duplicate 10 for each email thats 10x10. am i doing something wrong?
for($i =0; $i<11; $i++){
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email,$name);
$mail->Subject = "We wish you a merry Christmas";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($friendsEmails[$i], $friendsNames[$i]);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
Upvotes: 2
Views: 5845
Reputation:
No wonder you are sending multiple emails because in every iteration of your for loop you are just adding new addresses. Use PHPMailer::clearAllRecipients()
to remove data from the previous iteration before adding a new email address.
for($i =0; $i<11; $i++){
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email,$name);
$mail->Subject = "We wish you a merry Christmas";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($friendsEmails[$i], $friendsNames[$i]);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
$mail->clearAllRecipients(); // Clear all recipient types(to, bcc, cc).
}
Upvotes: 2
Reputation: 384
It's easier to put the e-mail addresses in key value pairs in an array. So the key is the name of your friend and the value the e-mail address. And use an foreach loop to iterate over the whole array without having to determine how many items are in the array.
Oh and reinstantiate your mail object every loop, to not have it send each last e-mail as well (don't know for sure, but that's what could be happening)
Try something like this:
$friendsEmails = array('name' => 'email_address');
foreach($friendsEmails as $name => $email) {
$mail = new Mailer();
$mail->SetFrom($name);
$mail->AddReplyTo($name);
$mail->Subject = "We wish you a merry Christmas";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($email, $name);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
Upvotes: 1
Reputation: 7763
Maybe at the end of every iteration you should clean your mail
object.
Another option is to instantiate one different mail class at the beginning of the loop.
Upvotes: 0