【问题标题】:PHPmailer duplicate email issue - conditional statement with $mail->Send()PHPmailer 重复电子邮件问题 - 带有 $mail->Send() 的条件语句
【发布时间】:2011-07-28 18:17:37
【问题描述】:

我遇到了一个奇怪的 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;   
    }  
} catch (phpmailerException $e) {  
    echo $e->errorMessage();  
}

上面的代码回显了“消息已发送”确认,但随后发送了两封电子邮件。如果我注释掉$mail->send() 行,我仍然会收到“消息已发送”确认,并且只收到一条消息。如果我删除条件语句并将 $mail->send() 行注释掉,则不会发送任何电子邮件。

为什么添加条件语句会导致发送电子邮件而不调用$mail->send() 方法?
添加自定义确认消息的正确方法是什么?

【问题讨论】:

    标签: php email phpmailer conditional-statements


    【解决方案1】:

    当您在条件中输入$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;   
    }
    

    【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 2019-04-16
    • 2013-08-03
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多