Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Multiple Mails In PHP Mailer

I have been writing a trigger that mails an email using PHP mailer. The problem with the code is that it is sending multiple mails to a single recipient. I even tried using the function singleTo but even that didn't seem to work.

$mail = new PHPMailer();

for($i = 0; $i <= sizeof($emailid); $i++)   {
    $mail->WordWrap = 50;                              
    $mail->IsHTML(true);                                 
    $mail->SingleTo = true;
    $mail->AddAddress($emailid[$i],$name[$i]);
    $mail->Subject = 'Some Subject';
    $mail->Body    = "Some Body";
    $mail->AltBody = "Some Body";

    $errornumber[$i] = 1;

    if(!$mail->Send()) {
       $errorinfo[$i] = $mail->ErrorInfo;
       $errornumber[$i] = 0;
    }
}
like image 202
Amit Nandan Periyapatna Avatar asked Feb 12 '26 11:02

Amit Nandan Periyapatna


1 Answers

AddAddress() simply adds a new address to the end of an array of addresses. If you want to send individual emails, per-address, you'll have to clear that list on each iteration, e.g.

for(...) {
   $mail->AddAddress(...);
   $mail->send();
   $mail->ClearAddresses();  // <---you need this line.
}

If a single user is receiving multiple emails, then you'd need some code to detect when you've already sent one, e.g.:

$sent = array();
for(...) {
   if (isset($sent[$email[$i]])) {
      continue; // check if sent already, skip if so
   }
   ...
   if ($mail->send()) {
     $sent[$email[$i]] = true; // flag address as already sent
   }
}
like image 141
Marc B Avatar answered Feb 15 '26 00:02

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!