为什么php - if($ mail-> send())无法正常工作

时间:2016-08-11 11:39:12

标签: php phpmailer

我曾尝试将此PHP代码用于网站联系我们页面。字段验证的错误消息正常工作。但是,由于发送错误信息,它无法正确处理$ result消息。

<?php
    if (isset($_POST["submit"]) && $_POST["submit"] == 'Send')
    {

        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $email = isset($_POST['email']) ? $_POST['email'] : '';
        $subject = isset($_POST['subject']) ? $_POST['subject'] : '';
        $message = isset($_POST['message']) ? $_POST['message'] : '';
        $human = isset($_POST['human']) ? intval($_POST['human']) : '';
        $error = array();

        // Check if name has been entered
        if (empty($name)) {
            $error['name'] = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error['email'] = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (empty($message)) {
            $error['message'] = 'Please enter your message';
        }

        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $error['human'] = 'Your anti-spam is incorrect';
        }

        // If there are no errors, send the email
        if (empty($error)) {
            $mail = new PHPMailer;

            $mail->isSMTP();
            $mail->SMTPDebug = 3;
            $mail->setFrom('from@example.com', 'Mailer');
            $mail->addAddress('example@example.net', 'User');


            $mail->Subject = $_POST['subject'];
            $mail->Body    = $_POST['message'];

            // From here the code is not working properly
            if ($mail->send()) {
                $result = '<div class="alert alert-success">Sorry there is a problem by sending your message. Please try again later.</div>';
            } else {
                //echo 'Mailer Error: ' . $mail->ErrorInfo;exit;
                $result = '<div class="alert alert-success">Thank you for your message and we will get back to you as soon as possible.</div>';
            }  
        }
    }
?>

您能否识别此代码的错误?

提前致谢。

2 个答案:

答案 0 :(得分:3)

您添加了错误的讯息。  在if ($mail->send()) {上,您已返回错误消息。

将支票更改为!$mail->send()该支票。

if (!$mail->send()) {

如果这不起作用,请尝试进行调试:

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

答案 1 :(得分:0)

尝试使用error功能

打印ErrorInfo
if(!$mail->Send()) {// Send not send
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";

}
相关问题