【发布时间】:2020-01-06 19:49:11
【问题描述】:
我有以下代码向我的客户发送电子邮件发货确认:
while ($i < count($tracked) ) {
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.office365.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support@mycompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('support@mycompany.com', 'mycompany');
$mail->addAddress($tracked[$i]['customers_email_address'], $tracked[$i]['customers_name']); // Add a recipient
$mail->addReplyTo('support@mycompany.com', 'mycompany');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = EMAIL_TEXT_SUBJECT;
$mail->Body = $html;
$mail->AltBody = 'Your order with mycompany.com has shipped';
$mail->send();
echo 'order confirmation sent to order#:'.$tracked[$i]['orders_id'].'<br/>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
$i++;
}
它似乎正在发送到多个电子邮件。我相信正在发生的事情是,在 while 循环中,每个新客户地址都被添加到列表中而不清除它。尽管消息似乎没有重复,但似乎没有发生什么?循环中的每次传递不会重复吗?
无论如何,我认为在尝试之前最好的做法是:
$mail = new PHPMailer(true);
这样每次循环的时候 $mail 对象都会被再次实例化。这合适吗?我知道 clearAllRecipients() 函数存在,但我也想确保身体也被清洁。
【问题讨论】:
-
按照answer below 中的建议处理您的地址问题,但我还建议您将除实际发送邮件(
$mail->send();和回显)之外的所有内容移到while 循环。没有理由在循环内做所有其他事情。做一次,然后重复使用。