PHPmailer如何实现Ajax表单

How to implement PHPmailer Ajax Form

我在使用此联系表(它在其他主机中有效)的网站服务器上遇到问题,但在这个新主机中不工作。支持中心告诉我必须使用 phpmailer class 但我不知道如何实现它。

我将不胜感激任何帮助!谢谢

代码

<?php
if ($_POST) {
    $to_email = "email@gmail.com"; //Recipient email, Replace with own email here
    $from_email = "email@gmail.com"; //From email address (eg: no-reply@YOUR-DOMAIN.com)

    //check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        $output = json_encode(array( //create JSON data
            'type' => 'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    }

    //Sanitize input data using PHP filter_var().
    $user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
    $user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
    $nac = filter_var($_POST["nac"], FILTER_SANITIZE_STRING);
    $phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
    $estado = filter_var($_POST["estado"], FILTER_SANITIZE_STRING);
    $delegacion = filter_var($_POST["delegacion"], FILTER_SANITIZE_STRING);
    $ocupacion = filter_var($_POST["ocupacion"], FILTER_SANITIZE_STRING);
    $message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

    //additional php validation
    if (strlen($user_name) < 10) { // If length is less than 10 it will output JSON error.
        $output = json_encode(array('type' => 'error', 'text' => 'Nombre demasiado corto.'));
        die($output);
    }
    if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) { //email validation
        $output = json_encode(array('type' => 'error', 'text' => 'Por favor ingresa un email válido.'));
        die($output);
    }
    if (!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)) { //check for valid numbers in phone number field
        $output = json_encode(array('type' => 'error', 'text' => 'Dígitos solamente en el teléfono.'));
        die($output);
    }
    if (strlen($estado) < 3) { //check emtpy estado
        $output = json_encode(array('type' => 'error', 'text' => 'Estado es requerido.'));
        die($output);
    }
    if (strlen($delegacion) < 4) { // If length is less than 10 it will output JSON error.
        $output = json_encode(array('type' => 'error', 'text' => 'Nombre de la delegación demasiado corto.'));
        die($output);
    }
    if (strlen($ocupacion) < 4) { // If length is less than 10 it will output JSON error.
        $output = json_encode(array('type' => 'error', 'text' => 'Nombre de la ocupación demasiado corto.'));
        die($output);
    }
    if (strlen($message) < 3) { //check emtpy message
        $output = json_encode(array('type' => 'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }

    //email body
    $message_body = "\n\n Nombre Completo: " . $user_name . "\n Email: " . $user_email . "\n Fecha de Nacimiento: " . $nac . "\n Teléfono: " . $phone_number . "\n Estado: " . $estado . "\n Delegación: " . $delegacion . "\n Ocupación: " . $ocupacion . " \n Mensaje: " . $message . "\n\n";

    ### Attachment Preparation ###
    $file_attached = false;
    if (isset($_FILES['file_attach'])) //check uploaded file
    {
        //get file details we need
        $file_tmp_name = $_FILES['file_attach']['tmp_name'];
        $file_name = $_FILES['file_attach']['name'];
        $file_size = $_FILES['file_attach']['size'];
        $file_type = $_FILES['file_attach']['type'];
        $file_error = $_FILES['file_attach']['error'];

        //exit script and output error if we encounter any
        if ($file_error > 0) {
            $mymsg = array(
                1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                3 => "The uploaded file was only partially uploaded",
                4 => "No file was uploaded",
                6 => "Missing a temporary folder"
            );

            $output = json_encode(array('type' => 'error', 'text' => $mymsg[$file_error]));
            die($output);
        }

        //read from the uploaded file & base64_encode content for the mail
        $handle = fopen($file_tmp_name, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $encoded_content = chunk_split(base64_encode($content));
        //now we know we have the file for attachment, set $file_attached to true
        $file_attached = true;
    }


    if ($file_attached) //continue if we have the file
    {
        $boundary = md5("sanwebe");

        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $user_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //plain text 
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($message_body));

        //attachment
        $body .= "--$boundary\r\n";
        $body .= "Content-Type: $file_type; name=\"$file_name\"\r\n";
        $body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n";
        $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
        $body .= $encoded_content;

    } else {
        //proceed with PHP email.
        $headers = "From:" . $from_email . "\r\n" .
            'Reply-To: ' . $user_email . '' . "\n" .
            'X-Mailer: PHP/' . phpversion();
        $subject = "ATEL Test";
        $body = $message_body;
    }

    $send_mail = mail($to_email, $subject, $body, $headers);


    if (!$send_mail) {
        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Could not send mail! Please check your PHP mail configuration.'
        ));
        die($output);
    } else {
        $output = json_encode(array(
            'type' => 'message',
            'text' => 'Hola ' . $user_name . ' Gracias por tu solicitud.'
        ));
        die($output);
    }
}

Helena 在 If 的 Else 中(附件) 你有: Reply-to header 仅以 \n 结尾 什么时候应该以 \r\n 结尾 你知道,所有 header 必须结束 \r\n

PHPMailer class 可以从这里下载:https://github.com/PHPMailer/PHPMailer(如果您在项目中使用它,也可以通过 Composer 下载)。

PHPMailer class 旨在简化 PHP 中发送电子邮件所需的代码。您在问题中引用的代码是我们在 class 之前使用的旧电子邮件发送方式的一个示例,例如 PHPMailer 存在。

简而言之,几乎所有您引用的代码都可以扔掉,代之以对 PHPMailer 的一次调用,以及为其设置参数的几行代码。

因此,扔掉您拥有的代码并使用 PHPMailer 文档中的示例之一重新开始。

文档中给出的示例应该足以让您入门;它们包括设置 to/from 地址、正文等,以及更复杂的内容,例如添加附件(同样,使用 PHPMailer 只需一行代码即可完成此操作)。 SO 上还有一大堆答案,举例说明了如何使用它。