接收ajax POST请求时,PHP mail()无法正常工作

我已经设置了一个使用jQuery ajax将POST请求发送到外部PHP文件的表单,该文件随后发送了电子邮件.我收到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变量中使用$_POST而不进行某种转义是不安全的.如果您这样保留,攻击者可以设置其他参数. Google将其用于生产之前.

如果您收到200,则可能是发送过程中的某些内容比Linux设置更容易阻止标头格式错误邮件.
但是,您应该使用提供的PHP代码收到格式错误的电子邮件,对吗?如果此后仍然发生错误,请回答此帖子.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...