PHP mail() 在收到 ajax POST 请求时不工作

PHP mail() not working when receiving an ajax POST request

我设置了一个表单,该表单使用 jQuery ajax 向外部 php 文件发送 POST 请求,然后由该文件发送电子邮件。我收到 200 状态代码,但没有收到电子邮件。

这里是 jQuery:

var ajaxSend = function(dataObj) {
        $.ajax({
            type: 'POST',
            url: 'send.php',
            data: dataObj,
            success: function() {console.log('Ajax Success!');}, 
            error: function() {console.log('Ajax Error!');},
            statusCode: {
                200: function() {console.log('200 Everything ok!');},
                400: function() {console.log('400 Bad request');},
                403: function() {console.log('403 Forbidden');},
                500: function() {console.log('500  Server error');}
            }
        });
}


    $('.contact-form input[type="submit"]').click(function(e) {

        if($('form')[0].checkValidity()) { //checks if insetred value meets the HTML5 required attribute
            e.preventDefault();
            var dataObj = {
                name:  $.trim($('.contact-form input[type="text"]').val()),
                email:  $.trim($('.contact-form input[type="email"]').val()),
                message:  $.trim($('.contact-form textarea').val())
            };

            ajaxSend(dataObj);

        } else { console.log("Invalid form"); }
    });

这是 php 文件:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $to_email = "myemail@gmail.com";
    $data = json_decode($_POST['dataObj']);    

    $subject = 'Email subject';
    $headers = 'From: '.$data['email'];
    $message  = 'Name: '.$data['name'].' \n';
    $message .= 'Email: '.$data['email'].' \n\n';
    $message .= 'Message:\n'.$data['message'].' \n';
    if (mail($to_email, $subject, $message, $headers)) {
        http_response_code(200);
    } else {
        http_response_code(500);
    }

} else {
    http_response_code(403);
}

虚拟主机是 windows,我已经尝试使用 POST 请求,但它工作正常,我收到了电子邮件。我认为这不是 php.ini 问题?

您的第一个问题是您在服务器端使用 $_POST['dataObj'],而数据仅在 $_POST 中可用(dataObj 是一个 javascript 变量名,不会传递给服务器)。例如,您可以通过阅读 $_POST['email'] 来获取电子邮件。尝试将您的 send.php 更改为:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $to_email = "myemail@gmail.com"; 

  $subject = 'Email subject';
  $headers = 'From: '.$_POST['email'];
  $message  = 'Name: '.$_POST['name'].' \n';
  $message .= 'Email: '.$_POST['email'].' \n\n';
  $message .= 'Message:\n'.$_POST['message'].' \n';
  if (mail($to_email, $subject, $message, $headers)) {
    http_response_code(200);
  } else {
    http_response_code(500);
  }

} else {
  http_response_code(403);
}

注意:直接在 $headers-variable 中使用 $_POST 而不进行某种转义是不安全的。如果你这样离开,攻击者可以设置额外的参数。 Google 在生产中使用它之前。

如果您收到 200,发送过程中的某些东西可能比您的 linux 设置更容易阻止格式错误 headers 的邮件。 但是,您应该收到一封格式错误的电子邮件,其中包含您提供的 php 代码,对吗?回答这个 post 以防错误仍然发生。