2

我正在尝试将电子邮件发送给 10 个不同的用户,我已将变量 $friendsEmails 放入一个包含 10 个不同电子邮件的数组中,但是看起来它将为每封 10x10 的电子邮件复制 10 个。难道我做错了什么?

  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!";
    }

       }
4

3 回答 3

2

难怪您要发送多封电子邮件,因为在 for 循环的每次迭代中,您只是在添加新地址。用于PHPMailer::clearAllRecipients()在添加新电子邮件地址之前从上一次迭代中删除数据。

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).
}
于 2012-12-21T08:54:25.000 回答
1

将电子邮件地址放在数组中的键值对中更容易。所以键是你朋友的名字,值是电子邮件地址。并使用 foreach 循环遍历整个数组,而无需确定数组中有多少项。

哦,并在每个循环中重新实例化您的邮件对象,不要让它也发送每封最后一封电子邮件(不确定,但这就是可能发生的事情)

尝试这样的事情:

$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!";
    }
}
于 2012-12-21T08:32:13.293 回答
0

也许在每次迭代结束时你应该清理你的mail对象。

另一种选择是在循环开始时实例化一个不同的邮件类。

于 2012-12-21T06:39:18.723 回答