如何为PHP中的电子邮件收件人创建有效的循环脚本(使用PHPMailer)

时间:2019-02-27 14:07:09

标签: php loops foreach while-loop phpmailer

我想为数据库中注册的2000个电子邮件地址建立一个电子邮件传递系统。

我遇到了错误的循环问题。这样1个收件人就能收到多封电子邮件。

请帮助,谢谢

这是一段脚本:

include "phpmailer/classes/class.phpmailer.php";
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPSecure = 'ssl';
    $mail->Host = "domain.com";
    $mail->SMTPDebug = 2;
    $mail->Port = 465;
    $mail->SMTPAuth = true;
    $mail->Username = "no-reply@domain.com";
    $mail->Password = "passsword";
    $mail->SetFrom("no-reply@domain.com","No Reply");
    $mail->Subject = $mail_subject;

    $query_email_list = mysqli_query($koneksi, "SELECT * FROM table");

    while($data_email = mysqli_fetch_array($query_email_list)){

        QRCode::png($data_email['email'], $tempdir. $data_email['email'].".png", $quality, $ukuran, $padding);

        $mail_body = file_get_contents('template/template_email_blast.html');
        $mail_body = str_replace('{email}', $data_email['email'], $mail_body);
        $mail_body = str_replace('{nama_agent}', $data_email['agent_name'], $mail_body);
        $mail_body = str_replace('{tempat_duduk}', $data_email['meja'], $mail_body);

        $mail->AddAddress($data_email['email'], $data_email['agent_name']);
        $mail->MsgHTML($mail_body);

        $sent = $mail->Send();
    }

1 个答案:

答案 0 :(得分:0)

由于AddAddress()是一种方法,它将在每个循环中添加一封电子邮件。

您将不得不循环清除地址或创建一个新对象。

更好的方法是清除地址。

$mail->clearAddresses(); // clear all [to] recipients.
$mail->clearAllRecipients(); // clear all recipients [to cc bcc] etc.

更新代码:

  while($data_email = mysqli_fetch_array($query_email_list)){

        QRCode::png($data_email['email'], $tempdir. $data_email['email'].".png", $quality, $ukuran, $padding);

        $mail_body = file_get_contents('template/template_email_blast.html');
        $mail_body = str_replace('{email}', $data_email['email'], $mail_body);
        $mail_body = str_replace('{nama_agent}', $data_email['agent_name'], $mail_body);
        $mail_body = str_replace('{tempat_duduk}', $data_email['meja'], $mail_body);
       // $mail->clearAddresses(); // clear all [to] recipients.
        $mail->clearAllRecipients(); // clear all recipients [to cc bcc] etc.
        $mail->AddAddress($data_email['email'], $data_email['agent_name']);
        $mail->MsgHTML($mail_body);

        $sent = $mail->Send();
    }

Reference docs