我遇到了PHPmailer(版本5.1)的一个奇怪的问题,我试图解决这个问题。我在这里看到了很多好的反馈,所以我想我会尝试一下。我发现当我尝试使用基于$mail->send()
的条件语句创建自定义确认消息时,我会收到重复的电子邮件。我可以使用phpmailer下载附带的通用testemail.php脚本复制它。这是代码:
require '../class.phpmailer.php';
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$mail->SMTPDebug = 1;
$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
$mail->Host = "mail.domain.com"; // SMTP server
$mail->Username = "username"; // SMTP server username
$mail->Password = "password"; // SMTP server password
$mail->IsSendmail();
$mail->From = "example_from@domain.com";
$mail->FromName = "First Last";
$to = "example@domain.com";
$mail->AddAddress($to);
$mail->Subject = "PHP Mailer test";
$message = "This is a test. \n";
$mail->Body = $message;
$mail->Send();
if ($mail->Send()) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
$mail->IsSendmail();
$mail->From = "example_from@domain.com";
$mail->FromName = "First Last";
$to = "example@domain.com";
$mail->AddAddress($to);
$mail->Subject = "PHP Mailer test";
$message = "This is a test. \n";
$mail->Body = $message;
$mail->Send();
if ($mail->Send()) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
以上代码回应了"消息已被发送"确认,但随后发送两封电子邮件。如果我注释掉} catch (phpmailerException $e) {
行,我仍会收到"消息已发送"确认,只收到一条消息。如果我删除条件语句并将
echo $e->errorMessage();
}$mail->send()
行注释掉,则不会发送任何电子邮件。
为什么添加条件语句会导致在不调用$mail->send()
方法的情况下发送电子邮件?添加自定义确认消息的正确方法是什么?
答案 0 :(得分:12)
当您将$mail->Send()
放入条件时,您实际上是在再次调用它,发送另一条消息,并检查是否已发送第二条消息。
如果你保持
if ($mail->Send()) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
并摆脱原始的,无条件的发送电话,你应该没事。
或者,如果您更清楚,或者您需要在其他地方进行某些处理,这取决于消息是否已成功发送,您可以执行基本相同的操作:
$status = $mail->Send();
if ($status) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}