尝试使用某些电子邮件输入发送表单时出现ajax错误

时间:2018-07-19 08:00:27

标签: php ajax email

尝试在页面上发送表单时收到此错误。当我在电子邮件输入字段中输入某些电子邮件地址(例如“我的名字”和@ gmail.com)时,发送邮件有效,但是当输入“假名”和@ gmail.com(gmail只是一个例子,我用gmx也得到相同的结果。)

我正在将swiftmailer与jquery验证程序一起使用。

因此它有时可以工作,而在其他情况下则无法工作。我试图缩小范围,这似乎与我在输入字段中输入的电子邮件地址有关,这让我感到非常困惑。

ajax 500 error

Ajax代码段:

$.ajax({
        url: 'mailer.php',
        method: 'post',
        data: formSerialized,
        dataType: 'text', // the type of data that you are expecting back from the server (text = no pre-processing occurs)
        error: function (jqXHR, textStatus, errorThrown) { // errorObject, errorText, errorHTTP

            // ajax request failed

            console.log(textStatus);
            console.log(errorThrown);

            ga('send', 'event', 'Kontaktformular', 'Ajax fehlgeschlagen');

            $('#contact-form .spinner').hide();
            $('#contact-form').hide();

            showFormFeedbackError(undefined, 'Ajax Error: ' + errorThrown);
        },
        success: function (responseData, textStatus, jqXHR) {

            // ajax request succeeded

            console.log(textStatus);
            console.log(responseData);

            $('#contact-form .spinner').hide();
            $('#contact-form').hide();

            // responseData is formatted according to the dataType parameter
            if ($.isNumeric(responseData)) {

                switch (parseInt(responseData)) {

                    case 1: // success
                        ga('send', 'event', 'Kontaktformular', 'Kontaktformular abgeschickt');
                        showFormFeedbackSuccess();
                        break;

                    default:
                        break;
                }
            } else {

                ga('send', 'event', 'Kontaktformular', 'Kontaktformular fehlgeschlagen');
                showFormFeedbackError(undefined, 'Mailer Error: ' + responseData);
            }
        },
        complete: function (jqXHR, textStatus) {

            // ajax request finished, whether in failure or success
            // called after success and error callbacks are executed

            resetForm();

            $('html, body').animate({
                scrollTop: $('#contact-form').siblings('.feedback').offset().top
            }, 1000);
        }
    });

mailer.php:

<?php

require_once __DIR__ . '/swiftmailer/lib/swift_required.php';

function fix_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);

    return $data;
}

function logContact($userName, $userEmail, $userTel, $userMsg) {
    global $msgAdmin, $msgUser;

    $return = false;

    // create connection
    $conn = new mysqli('localhost', 'sql_myserver', 'pw', 'dbName');

    // check connection
    if ($conn->connect_errno) {
        $msgAdmin .= 'Failure: MySQLi: Database connection failed: ' . $conn->connect_error;
        //$msgUser .= 'Failure: MySQLi: Database connection failed: ' . $conn->connect_error;
    } else {
        $charset = 'utf8';

        // set default client character set
        // will affect real_escape_string()
        if (!$conn->set_charset($charset)) {
            $msgAdmin .= 'Warning: MySQLi: Cannot set default client character set of database connection to "' . $charset . '"';
            //$msgUser .= 'Warning: MySQLi: Cannot set default client character set of database connection to "' . $charset . '"';
        }

        $userName = $conn->real_escape_string($userName);
        $userEmail = $conn->real_escape_string($userEmail);
        $userTel = $conn->real_escape_string($userTel);
        $userMsg = $conn->real_escape_string($userMsg);

        $queryString = 'INSERT INTO contact (contact_datetime, user_name, user_email, user_tel, user_msg) VALUES (NOW(), "' . $userName . '", "' . $userEmail . '", "' . $userTel . '", "' . $userMsg . '")';

        if ($conn->query($queryString)) {
            //$msgAdmin .= 'Info: MySQLi: Database insertion of ' . $conn->affected_rows . ' row(s)';
            //$msgUser .= 'Info: MySQLi: Database insertion of ' . $conn->affected_rows . ' row(s)';

            $return = true;
        } else {
            $msgAdmin .= 'Failure: MySQLi: Database insertion failed: ' . $conn->sqlstate . ' (sqlstate error code)';
            //$msgUser .= 'Failure: MySQLi: Database insertion failed: ' . $conn->sqlstate . ' (sqlstate error code)';
        }
    }

    $conn->close();

    return $return;
}

$error = '';

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    if ($_POST && is_array($_POST)) {
        if (isset($_POST['g-recaptcha-response'])) {
            $response = $_POST['g-recaptcha-response']; // user response token provided by recaptcha (can only be verified once)
            $secret = 'recaptchasecretkey'; // shared key between your site and recaptcha

            // verify user response token with recaptcha api request
            // recaptcha api response is a json object
            // https://developers.google.com/recaptcha/docs/verify

            $verify = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $response));
            //var_dump($verify);

            if ($verify->success === true) {
                $msg_email_to =  array('myname@mycompany.com' => 'MyName');
                $msg_email_cc =  array(/*'' => 'Name', 't' => 'Name'*/);
                $msg_email_bcc = array(/*'' => 'Name', '' => 'Name'*/);

                $msg_project = 'MyClient';
                $msg_subject = 'MyCompany Anfrage zu Projekt: ' . $msg_project;
                $msg_intro = 'Dieser Kunde kommt von MyCompany';

                $txt_na = 'keine Angabe';
                $txt_empty = 'leere Eingabe';

                $msg_sex = $msg_name = $msg_email_from = $msg_tel = $msg_msg = $msg_host = $msg_ip = $txt_na;
                $user_copy = false;

                if ($_POST['sex']) {
                    $msg_sex = fix_input($_POST['sex']);
                    if (empty($msg_sex)) {
                        $msg_sex = $txt_empty;
                    }
                }
                if ($_POST['name']) {
                    $msg_name = fix_input($_POST['name']);
                    if (empty($msg_name)) {
                        $msg_name = $txt_empty;
                    }
                }
                if ($_POST['email']) {
                    $msg_email_from = strtolower(fix_input($_POST['email']));
                    if (empty($msg_email_from)) {
                        $msg_email_from = $txt_empty;
                    }
                }
                if ($_POST['tel']) {
                    $msg_tel = fix_input($_POST['tel']);
                    if (empty($msg_tel)) {
                        $msg_tel = $txt_empty;
                    }
                }
                if ($_POST['msg']) {
                    $msg_msg = fix_input($_POST['msg']);
                    if (empty($msg_msg)) {
                        $msg_msg = $txt_empty;
                    }
                }
                if ($_POST['user-copy']) {
                    $user_copy = true;
                }

                if ($_SERVER['REMOTE_HOST']) {
                    $msg_host = $_SERVER['REMOTE_HOST'];
                    if (empty($msg_host)) {
                        $msg_host = $txt_empty;
                    }
                }
                if ($_SERVER['REMOTE_ADDR']) {
                    $msg_ip = $_SERVER['REMOTE_ADDR'];
                    if (empty($msg_ip)) {
                        $msg_ip = $txt_empty;
                    }
                }

                // sanitize from email
                $msg_email_from = filter_var($msg_email_from, FILTER_SANITIZE_EMAIL);

                // test invalid from email
                //$msg_email_from = 'xxx';

                // validate from email
                if (!filter_var($msg_email_from, FILTER_VALIDATE_EMAIL) === false) {

                    $msg_composite_html = $msg_intro . '<br>' .
                                'Projekt: ' . $msg_project . '<br><br>--<br><br>' .
                                $msg_msg . '<br><br>--<br><br>' .
                                'Name: ' . $msg_sex . ' ' . $msg_name . '<br>' .
                                'E-Mail: ' . $msg_email_from . '<br>' .
                                'Telefon: ' . $msg_tel;

                    $msg_composite_plain = $msg_intro . PHP_EOL .
                                'Projekt: ' . $msg_project . PHP_EOL . '--' . PHP_EOL .
                                $msg_msg . PHP_EOL . '--' . PHP_EOL .
                                'Name: ' . $msg_sex . ' ' . $msg_name . PHP_EOL .
                                'E-Mail: ' . $msg_email_from . PHP_EOL .
                                'Telefon: ' . $msg_tel;

                    $message = Swift_Message::newInstance();
                    $message->setFrom(array($msg_email_from => $msg_sex . ' ' . $msg_name)); // associative array

                    if (!empty($msg_email_to))  { $message->setTo($msg_email_to); }
                    if (!empty($msg_email_cc))  { $message->setCc($msg_email_cc); }
                    if (!empty($msg_email_bcc)) { $message->setBcc($msg_email_bcc); }

                    $message->setSubject($msg_subject);
                    $message->setBody($msg_composite_html, 'text/html');
                    $message->addPart($msg_composite_plain, 'text/plain');  // optional alternative body
                    $message->setPriority(2); // int between 1 and 5 (1 = highest priority)

                    // to send the message create a Transport (actually does the sending), use it to create the Mailer, then you use the Mailer to send the message.

                    $transport = Swift_SmtpTransport::newInstance('127.0.0.1', 25);
                    $transport->setUsername('');
                    $transport->setPassword('');
                    $mailer = Swift_Mailer::newInstance($transport);

                    // if you set 2 To: recipients and 3 Bcc: recipients in the message and all of the recipients are delivered to successfully then the value 5 will be returned.
                    // if none of the recipients could be sent to then 0 will be returned, which equates to a boolean false.
                    $failedRecipients = array();
                    $result = $mailer->send($message, $failedRecipients);

                    if ($result && empty($failedRecipients)) {
                        // success
                        echo '1';
                        logContact($msg_sex . ' ' . $msg_name, $msg_email_from, $msg_tel, $msg_msg);

                        $msg_user_copy_html =   'Vielen Dank, Ihre Vormerkung ist AM WOLLWERK eingetroffen!' . PHP_EOL .
                                    'Wir informieren Sie umgehend, sobald das Projekt in die Vermarktung gelangt.' . PHP_EOL . ' ' . PHP_EOL .
                                    'Projekt: ' . $msg_project . PHP_EOL .
                                    $msg_msg . PHP_EOL . ' ' . PHP_EOL .
                                    'Name: ' . $msg_sex . ' ' . $msg_name . PHP_EOL .
                                    'E-Mail: ' . $msg_email_from . PHP_EOL .
                                    'Telefon: ' . $msg_tel/* . '<br><br>--<br><br>' .
                                    'Host: ' . $msg_host . '<br>' .
                                    'IP: ' . $msg_ip*/;

                        if ($user_copy === true) {
                            $headers = 'From: myclient@myclient.com' . PHP_EOL . 'Reply-To: myname@mycompany.com' . PHP_EOL . 'X-Mailer: PHP/' . phpversion();
                            mail('myname@mycompany.com', 'User Copy: ' . $msg_project, $msg_user_copy_html, $headers);  
                        }
                    } else {
                        $comma_separated2 = implode(', ', $failedRecipients);
                        if (!$result) {
                            $error .= 'none of the recipients could be sent to (' . $comma_separated2 . ')';
                            echo 'none of the recipients could be sent to (' . $comma_separated2 . ')';
                        } else {
                            $error .= 'some of the recipients could not be sent to (' . $comma_separated2 . ')';
                            echo 'some of the recipients could not be sent to (' . $comma_separated2 . ')';
                        }
                    }
                } else {
                    $error .= 'not valid from email (' . $msg_email_from . ')';
                    echo 'not valid from email (' . $msg_email_from . ')';
                }
            } else {
                $comma_separated = implode(', ', $verify->{'error-codes'});

                $error .= 'recaptcha user response token not verified (' . $comma_separated . ')';
                echo 'recaptcha user response token not verified (' . $comma_separated . ')';
            }
        } else {
            $error .= 'no recaptcha user response token';
            echo 'no recaptcha user response token';
        }
    } else {
        $error .= 'not post';
        echo 'not post';
    }
} else {
    $error .= 'not xmlhttprequest';
    echo 'not xmlhttprequest';
}

if ($error !== '') {
    $headers = 'From: myname@mycompany.com' . PHP_EOL . 'Reply-To: myname@mycompany.com' . PHP_EOL . 'X-Mailer: PHP/' . phpversion();

    // mail alert
    mail('myname@mycompany.com', 'Mailer Error: ' . $msg_project, $error, $headers);
}

?>

0 个答案:

没有答案