doufu1504 2019-03-29 14:03
浏览 73
已采纳

尝试提交此电子邮件表单时出现错误[重复]

This question already has an answer here:

I have made a form that emails the info entered in the fields but I am getting an error when filled out.

Could not send mail! Please check your PHP mail configuration.

All the code seems good but I can't find the cause of the error. The error shows once I try to submit the form (which is the error message meant to show on a send mail error). Any help is greatly appreciated!!

I should mention that there are 2 forms in the directory; Form "1", uses the "1" versions of the JS and PHP files, Form "2' uses the "2" version. They do not share the JS and PHP files.

<form id="email-form2" name="email-form2" method="POST" data-name="Insurance Form">
  Enter Name
  <input class="w-input text-field" id="name" type="text" placeholder="First name and last name" name="name" data-name="Name" required> Email
  <input class="w-input text-field" id="email" type="email" name="email" placeholder="Enter your email address" data-name="Email" required> Date of Birth
  <input class="w-input text-field" id="date" type="date" name="date" data-name="Date" required> Gender
  <input class="w-input text-field" id="gender" type="text" placeholder="Male or Female" name="gender" data-name="Gender" required> Member ID
  <input class="w-input text-field" id="member" type="text" placeholder="Member number" name="member" data-name="Member" required> Policy ID
  <input class="w-input text-field" id="policy" type="text" placeholder="Policy number" name="policy" data-name="Policy" required>
  <div class="div-spc">
    <button class="w-button button no-margin" type="submit">Submit Form</button>
  </div>
</form>
<?php
  if($_POST) 
  {
    $to_Email = "email@email.com"; //Replace with recipient email address

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

      die($output);
  }

  //check $_POST vars are set, exit if any missing
  if (!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userDate"]) || !isset($_POST["userGender"]) || !isset($_POST["userMember"]) || !isset($_POST["userPolicy"])) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
    die($output);
  }

  //additional php validation
  if (empty($_POST["userName"])) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
    die($output);
  }

  if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
    die($output);
  }

  if (empty($_POST["userMember"])) 
  {  
    $output = json_encode(array('type'=>'error', 'text' => 'Need Member ID number!'));
    die($output);
  }

  if (empty($_POST["userGender"])) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter Male or Female!'));
    die($output);
  }
  if (empty($_POST["userPolicy"])) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Need Policy ID number!'));
    die($output);
  }

  if (empty($_POST["userDate"])) 
  {
    $output = json_encode(array('type'=>'error', 'text' => 'Please fill out birth date!'));
    die($output);
  }

  //proceed with PHP email.
  $headers = 'From: '.$_POST["userEmail"].'' . "
" .
    'Reply-To: '.$_POST["userEmail"].'' . "
" .
    'X-Mailer: PHP/' . phpversion();

  // send mail
  $sentMail = @mail($to_Email, $_POST["userName"], $_POST["userDate"], $_POST["userGender"], $_POST["userMember"], $_POST["userPolicy"], $headers);

  if (!$sentMail) 
  {
    $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' => 'Hi '.$_POST["userName"] .' Thank you for your email'));
    die($output);
  }
}
?>
$(document).on("ready", function() {
  $("#email-form2 [type='submit']").click(function(event) {
    event.preventDefault();
    //get input field values
    var user_name = $('input[name=name]').val()
    var user_email = $('input[name=email]').val()
    var user_date = $('input[name=date]').val()
    var user_gender = $('input[name=gender]').val()
    var user_member = $('input[name=member]').val()
    var user_policy = $('input[name=policy]').val()

    //data to be sent to server
    post_data = {
      'userName': user_name,
      'userEmail': user_email,
      'userGender': user_gender,
      'userMember': user_member,
      'userPolicy': user_policy,
      'userDate': user_date
    }

    //Ajax post data to server
    $.post('contact_me2.php', post_data, function(response) {
      //load json data from server and output message    
      if (response.type == 'error') {
        output = '<div class="error-message"><p class="from">' + response.text + '</p></div>'
      } else {
        output = '<div class="success-message"><p class="seuccses">' + response.text + '</p></div>'

        //reset values in all input fields
        $('#email-form2 input').val('')
      }
      $("#result").hide().html(output).slideDown()
    }, 'json')
  });

  //reset previously set border colors and hide all message on .keyup()
  $("#email-form2 input").keyup(function() {
    $("#result").slideUp()
  })
});
</div>
  • 写回答

1条回答 默认 最新

  • doulong6761 2019-03-29 16:02
    关注

    If you take a look at the documentation for mail(), you'll see that the function accepts 5 parameters.

    Now, how many parameters are you sending it in your code? (answer: 7). Can you see how that might be a problem? Also you're using @ at the start of mail() which will suppress any errors which might have been thrown as a result.

    Even if it doesn't error, you're sending it nonsensical data for everything after the $message parameter, and that's why it's not working. I expect perhaps you really want to join all those various fields (username, gender, date, policy, etc) together in a single string, with some formatting such as spaces and newlines etc, so that it forms a coherent message body - rather than just firing them all at the mail() function and hoping it rearranges them into something readable (which, to be clear, it can't and won't).

    To give you a start, try this:

    $subject = "Some subject";
    $message = $_POST["userName"]." ".$_POST["userDate"]." ". $_POST["userGender"]." ".$_POST["userMember"]." ".$_POST["userPolicy"];
    $sentMail = mail($to_Email, $subject, $message, $headers); 
    

    Here I have

    a) declared the subject and message as separate variables, to improve clarity and readability.

    b) joined the various POST field values together into a single string, separated by spaces. In PHP, joining strings (also called "concatenation") is done using the . operator - you simple place it in between two strings that you want to join to each other.

    You can add more content yourself inside the double-quoted areas, and change the subject line to your liking.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大