PHPmailer duplicate email issue - conditional stat

2019-02-24 12:12发布

问题:

I came across a bizarre issue with PHPmailer (version 5.1) that I'm trying to work around. I've seen quite a bit of good feedback on here, so I thought I would give it a try. I've found that when I attempt to create a customized confirmation message with a conditional statement based on $mail->send(), I receive duplicate emails. I can duplicate it with the generic testemail.php script that comes with the phpmailer download. Here's the code:

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;   
}  

} catch (phpmailerException $e) {
echo $e->errorMessage();
}

The above code echoes the "Message has been sent" confirmation, but then sends two emails. If I comment out the $mail->send() line, I still receive the "message has been sent" confirmation and only get one message. If I remove the conditional statement and leave the $mail->send() line commented out, no email is sent.

Why does adding a conditional statement cause an email to be sent without calling the $mail->send() method? What is the proper way of adding a customized confirmation message?

回答1:

When you put $mail->Send() in your conditional, you're actually calling it again, sending another message, and checking if that second message was sent.

If you just keep

if ($mail->Send()) {  
    echo 'Message has been sent.';  
} else {  
    echo "Mailer Error: " . $mail->ErrorInfo;   
}

and get rid of the original, unconditional Send call, you should be fine.

Alternatively, if it's clearer for you or if you need to do some processing elsewhere that depends on whether the message was successfully sent, you could do the essentially equivalent:

$status = $mail->Send();
if ($status) {  
    echo 'Message has been sent.';  
} else {  
    echo "Mailer Error: " . $mail->ErrorInfo;   
}