首页 > 解决方案 > 转移到另一台服务器后PHPMailer失败

问题描述

这让我的大脑崩溃了。我在两台不同的服务器上有完全相同的代码。它在一个中发送 SMTP 邮件没有问题,而在另一个中失败。控制台很干净。而且我没有办法调试任何东西,因为我不知道到底是什么失败了。我可以借一双眼睛吗?

这是一个带有验证码的简单表格。通过或失败后,它会以成功/失败模式进行回答。如果失败,它会停留在联系页面上以纠正错误并重新发送。如果通过,则在关闭成功模式后刷新屏幕。

我的联系页面<head>

    <script>
        $(document).ready(function() {

            var request;

            $("#contactForm").submit(function(event){
                event.preventDefault();

                // Abort any pending request
                if (request) {
                    request.abort();
                }

                // setup some local variables
                var $form = $(this);

                // Let's select and cache all the fields
                var $inputs = $form.find("input, select, button, textarea");

                // Serialize the data in the form
                var serializedData = $form.serialize();

                // Let's disable the inputs for the duration of the Ajax request.
                // Note: we disable elements AFTER the form data has been serialized.
                // Disabled form elements will not be serialized.
                $inputs.prop("disabled", true);

                request = $.ajax({
                    url: "sendContactMail.php",
                    type: "post",
                    data: serializedData
                });

                // Callback handler that will be called on success
                request.done(function (response, textStatus, jqXHR){

                    if (response.status == 0) {
                        // Success! Do something successful, like show success modal
                        jQuery.noConflict();
                        $('#successEmail').modal('show');
                    } else {
                        // Oh no, failure - notify the user
                        jQuery.noConflict();
                        $('#failEmail').modal('show');
                    }

                    $( "#failBtn" ).click(function() {
                        jQuery.noConflict();
                        $('#failEmail').modal('hide');
                    });

                    $( "#passBtn" ).click(function() {
                        window.location.reload();
                    });

                });

                // Callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    // Say you have a <div class="message"></div> somewhere, maybe under your form
                    //$('.message').html('Error: ' + textStatus + ', ' + errorThrown)
                });

                // Callback handler that will be called regardless
                // if the request failed or succeeded
                request.always(function () {
                    // Reenable the inputs
                    $inputs.prop("disabled", false);
                });
            });
        });
    </script>

联系表:

<form id="contactForm" class="form margin-alpha-top" method="POST"> 
    <div class="form__group">
        <label class="form__label" for="inputSubject">Subject</label>
        <input id="inputSubject" name="subject" type="text" class="form__field">
    </div>
    <div class="form__group">
        <label class="form__label" for="inputName">Name *</label>
        <input id="inputName" name="name" type="text" class="form__field" required="">
    </div>
    <div class="form__group">
        <label class="form__label" for="inputEmail">E-mail *</label>
        <input id="inputEmail" name="email" type="email" class="form__field" required="">
    </div>
    <div class="form__group">
        <label class="form__label" for="inputPhone">Phone</label>
        <input id="inputPhone" name="phone" type="text" class="form__field">
    </div>
    <div class="form__group form-group--extended">
        <label class="form__label form__label--extended" for="inputMessage">Message *</label>
        <textarea id="inputMessage" name="message" class="form__field form__field--extended" rows="6" required=""></textarea>
    </div>
    <div class="row captcha">
        <div class="column-xs-12 column-sm-4 column-md-4 xs-center">
        </div>
        <div class="column-xs-6 column-sm-4 column-md-4 xs-center">
            <img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
            <br/>
            <input type="text" name="captcha_code" size="10" maxlength="6" />
            <br/>
            <a href="#" id="secureText" onclick="document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); return false">
                <small>Refresh Image</small>
            </a>
        </div>
        <div class="column-xs-6 column-sm-4 column-md-4 xs-center">
            <div class="form__group submit-button">    
                <button 
                    type="submit" 
                    class="form__button button button--gamma margin-beta-bottom" 
                    id="btnSubmit">
                    <span class="button__text">Send</span>
                </button>
            </div>
        </div>
    </div>                                        
</form>

我的 sendContactMail.php 脚本

<?php
session_start();

$msg = '';


use PHPMailer\PHPMailer\PHPMailer;

require './mail/PHPMailer.php';
require './mail/Exception.php';
require './mail/SMTP.php';
require './mail/PHPMailerAutoload.php';

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

$securimage = new Securimage();

//Don't run this unless we're handling a form submission
if (array_key_exists('email', $_POST)) {

    date_default_timezone_set('Etc/UTC');

    //Create a new PHPMailer instance
    $mail = new PHPMailer;

    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';                        // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'lotusms@outlook.com';              // SMTP username
    $mail->Password = '********';                         // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    $mail->setFrom('lotusms@outlook.com', 'Mailer');
    $mail->addAddress('lotusms@outlook.com', 'Luis Silva');


    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $subject = isset($_POST['subject']) ? $_POST['subject'] : null;
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $phone = isset($_POST['phone']) ? $_POST['phone'] : null;
    $message = isset($_POST['message']) ? $_POST['message'] : null;


    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = $_POST['subject'];
        $mail->isHTML(true);
        $mail->Body = <<<EOT
<div style="width:100%">
<div><label style="color: #044F69; font-weight:bold">Subject:</label> <span>{$_POST['subject']}</span></div>
<div><label style="color: #044F69; font-weight:bold">Email:</label> <span>{$_POST['email']}</span></div>
<div><label style="color: #044F69; font-weight:bold">Name:</label> <span>{$_POST['name']}</span></div>
<div><label style="color: #044F69; font-weight:bold">Phone:</label> <span>{$_POST['phone']}</span></div>
<div><label style="color: #044F69; font-weight:bold">Message:</label> <span>{$_POST['message']}</span></div>
</div>
EOT;

        if ($securimage->check($_POST['captcha_code']) == false) {
            $response = [
                'status'=> 1,
                'msg'   => 'CAPTCHA test failed!'
            ];
        } else {
            //Send the message, check for errors
            if (!$mail->send()) {
                // Generate a response in this failure case, including a message and a status flag
                $response = [
                    'status'=> 1,
                    'msg'   => 'Sorry, something went wrong. Please try again later.'
                ];
            } else {
                // Generate a response in the success case, including a message and a status flag
                $response = [
                    'status'=> 0,
                    'msg'   => 'Success!'
                ];
            }
        }
    } else {
        // Generate a response in this failure case, including a message and a status flag
        $response = [
            'status'=> 1,
            'msg'   => 'Invalid email address, message ignored.'
        ];
    }
}
// Add the response to the session, so that it will be available after reload
$_SESSION['response'] = $response;

// Finally display the response as JSON so calling JS can see what happened
header('Content-Type: application/json');
echo json_encode($response);

?>

我在其他站点上运行的完全相同的设置也可以正常工作。我没看到什么?它如何在一台服务器上工作而不在另一台服务器上工作?

我知道在这里发布真实站点不是一个好习惯,但是如果您想看到它们通过和失败,也许它可以帮助您以某种方式进行调试,您可以。这是一个警察局网站。完全安全。

失败的站点(来自我无法控制的专用服务器)

通过站点(来自 HostGator)

非常感谢你。这是我捐赠的一个无偿网站,所以我仅限于我可以招募多少帮助

标签: phpphpmailer

解决方案


最近我在使用 PHP Mailer 时遇到了非常相似的问题。首先,我们知道它必须与服务器有关,因为该站点在开发服务器上运行,而不是在实时服务器中。最有可能发生错误是因为SMTP 服务器连接不工作或实时系统中的 SMTP 服务器拒绝您的邮件请求(但是,由于不同的 PHP 版本、不同的变量、不同的 php,您的代码之前可能已经出现问题.ini,...)。

因此,我们必须调试才能发现问题。调试 PHPMailer 有很好的记录:https ://github.com/PHPMailer/PHPMailer/wiki/SMTP-Debugging

这是您应该尝试调试问题的方式(代码缩短):

    //Create a new PHPMailer instance
    $mail = new PHPMailer;

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';                        // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'lotusms@outlook.com';              // SMTP username
    $mail->Password = '********';                         // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    $mail->setFrom('lotusms@outlook.com', 'Mailer');
    $mail->addAddress('lotusms@outlook.com', 'Luis Silva');


    $mail->Subject = $_POST['subject'];
    $mail->isHTML(true);
    $mail->Body = "...";


    $mail->SMTPDebug = 4; // Lowest level, you may also use 1, 2 or 3
    $mail->Debugoutput = 'text'; // if this does not work, use 'error_log' or even a custom closure

    var_dump($mail);

    $send = $mail->send());

    var_dump($send);

如果出现问题,您应该立即在您var_dump的 s 或由SMTPDebugandDebugoutput属性创建的输出中看到问题。

您的问题有多种可能的原因,关键是在您的实时环境中(但不一定在您的实时站点上)正确调试您的代码

如果$mail->Debugoutput='text';不起作用,请尝试'error_log'查看日志文件,甚至为此目的编写自定义闭包(请参阅文档)。


推荐阅读