我正在设置PHP Mailer以将批量电子邮件发送给许多收件人。电子邮件已成功发送,但是从我的SQL查询中,已发送的电子邮件是重复的。我在 W3schools 上读过有关使用distinct防止电子邮件重复的信息,但是我尝试使用它,但是电子邮件仍然多次发送。
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/Exception.php';
require 'php-mailer/PHPMailer.php';
require 'php-mailer/SMTP.php';
// Configuring SMTP server settings
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 25;
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->setFrom('noreply@myemail.com', 'Some Text');
$mail->Subject = "Expired Operating Permit";
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysqli = mysqli_connect('localhost', 'root', '');
mysqli_select_db($mysqli, 'dbname');
$sql = "SELECT DISTINCT permits.*, customers.company_name,customers.email FROM permits JOIN customers ON customers.id = permits.cus_id WHERE permits.date_of_expiry < '".date('Y-m-d H:i:s')."' AND permits.permit_type = 1";
$result =mysqli_query($mysqli,$sql);
foreach ($result as $row) {
$mail->addAddress($row['email'], $row['company_name']);
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("@", "@", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
break; //Abandon sending
} else {
echo "Message sent to :" . $row['company_name'] . ' (' . str_replace("@", "@", $row['email']) . ')<br />';
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
$mail->clearAttachments();
}?>
我希望电子邮件只能发送一次,但是可以多次发送。