How to use phpmailer to send email to multiple addresses one by one?

I need a loop foreachto send email to multiple addresses every time I run the PHP code:

$id = "a@a.com
    b@c.com
    d@e.com";

$new = explode("\n", $id);

foreach ($new as $addr) {
    $mail->addAddress($addr);
}

if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

But he put all the email addresses in the box toand then sent an email.

Therefore, when someone receives an email, he can see all the email recipients in the field to.

I want the code to send emails one by one.

+4
source share
5 answers

The problem is that you are actually adding multiple recipients addAddress()before sending emails.

, ...

$mail->addAddress('a@a.com');    // Add a recipient
$mail->addAddress('b@c.com');    // Add a another recipient
$mail->addAddress('d@e.com');    // Add a another recipient

TO a@a.com, b@c.com, d@e.com
... .

one by one, mail .
( , ).

+1

clearAddresses() (https://goo.gl/r5TR2B) , :

$id = "a@a.com
    b@c.com
    d@e.com";

$new = explode("\n", $id);

foreach ($new as $addr) 
{
    $mail->clearAddresses();
    $mail->addAddress($addr);

    if (!$mail->send()) 
    {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } 
    else 
    {
        echo "Message sent!";
    }
}

, , .

+4

PHPMailer. CC (EDIT: BCC). .

$mail = new PHPMailer();
$mail->AddBCC('a@a.com');
+2

, . , . :

<?php
$people = array("person1@mail.com", "person2@mail.com", "person3@mail.com");

foreach($people as $p) {
    $message = "Line 1\r\nLine 2\r\nLine 3";
    mail($p, 'My Subject', $message);
};

?>

You can also use the BCC field (this is a blind carbon copy).

PHPMailer, as suggested earlier, is good, but you should note that CC (plain copy) will still be visible to other people on the mailing list.

0
source

Initiate a new PHPMailer inside foreach and send an email after that.

$id = "a@a.com
b@c.com
d@e.com";

$new = explode("\n", $id);

foreach ($new as $addr) {
   $mail = new PHPMailer();
   $mail->addAddress($addr);

   if (!$mail->send()) {
      echo "Mailer Error: " . $mail->ErrorInfo;
   } else {
      echo "Message sent!";
   }
}
0
source

Source: https://habr.com/ru/post/1598656/


All Articles