PHPMailer发送重复电子邮件

3

PHPMailer

<?php
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->IsHTML(true);
    $mail->SMTPSecure = "tls";
    $mail->Mailer = "smtp";
    $mail->Host = "smtp.office365.com";
    $mail->Port = 587;
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = "xxx";
    $mail->Password = "xxx";
    $mail->setFrom('xxx', 'Website');

    //Send to Admin
    $AdminEmail = 'admin.example@gmail.com';
    $mail->AddAddress($AdminEmail, $AdminName);
    $mail->Subject  = "This is an email";
    $mail2 = clone $mail;
    $body = 'Hi Admin. This is an email';
    $mail->Body = $body;

    if(!$mail->Send()) {
    echo 'Message was not sent.';
    echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
    echo 'Message has been sent.';
    }

    //Send to User
    $UserEmail = 'user.example@gmail.com';
    $mail2->AddAddress($UserEmail, $UserName);
    $body2 = 'Hi User. This is an email';
    $mail2->Body = $body2;

    if(!$mail2->Send()) {
    echo 'Message was not sent.';
    echo 'Mailer error: ' . $mail2->ErrorInfo;
    } else {
    echo 'Message has been sent.';
    }
?>

我遇到了一个问题,就是在发邮件时,管理员会同时收到$mail$mail2的邮件,但他们只应该收到$mail的邮件。而用户没有这个问题,可以正常地接收到$mail2的邮件。我尝试了使用 $mail->ClearAddresses(); 但问题仍然存在。请问这个问题是什么?


3
我猜您先执行了AddAddress函数,然后克隆了变量。也许在添加管理员的电子邮件地址之前克隆变量会更好? - Casper
@Casper 哇,这是一个简单的错误,我没有意识到。谢谢!我已经卡了几个小时了 :| - Athirah Hazira
@Casper,你可以发布答案吗?这样我就可以接受它了。谢谢! - Athirah Hazira
如果这解决了问题,邀请他把评论作为答案发布并接受。这会奖励他并帮助未来查看该问题的其他人。 - Mawg says reinstate Monica
2
你根本不需要克隆它,也不需要创建另一个实例 - 你可以直接重复使用同一个实例。只需在第二次调用send之前调用clearAllRecipients,添加其他收件人并设置新的Body值即可。 - Synchro
2个回答

3

在添加管理员的地址和其他信息之前,克隆电子邮件变量。(如评论中所建议的)


1

您需要为管理员和用户电子邮件创建不同的对象。

//Send to Admin
$mail = new PHPMailer;
$mail->IsHTML(true);
$AdminEmail = 'admin.example@gmail.com';
$mail->AddAddress($AdminEmail, $AdminName);
$mail->Subject  = "This is an email";
$mail2 = clone $mail;
$body = 'Hi Admin. This is an email';
$mail->Body = $body;

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

//Send to User
$mail = new PHPMailer;
$mail->IsHTML(true);
$UserEmail = 'user.example@gmail.com';
$mail->AddAddress($UserEmail, $UserName);
$body2 = 'Hi User. This is an email';
$mail->Body = $body2;

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接