drf97973 2017-09-04 04:33
浏览 50
已采纳

PHP表单发送正确但我没有收到电子邮件[重复]

This question already has an answer here:

I am trying to create a PHP contact form by this bootstrap template: https://startbootstrap.com/template-overviews/agency/

This template is working find in my local host, Email correctly send and I received the email.

but when I use their code in my own website, it always said Email correctly send, but I never receive the Email

The following is the code

HTML:

<!-- contact form begin -->
            <span id="form-title">Let's Get In Touch</span>
            <div class="form-group">
              <input class="input-style1 form-control" id="name" type="text" placeholder="Your Name *" required data-validation-required-message="Please enter your name.">
              <p class="help-block text-danger"></p>
            </div>
            <div class="form-group">
              <input class="input-style1 form-control" id="email" type="email" placeholder="Your Email *" required data-validation-required-message="Please enter your email address.">
              <p class="help-block text-danger"></p>
            </div>
            <div class="form-group">
              <input class="input-style1 form-control" id="phone" type="tel" placeholder="Your Phone *" required data-validation-required-message="Please enter your phone number.">
              <p class="help-block text-danger"></p>
            </div>
            <div class="form-group">
              <textarea rows="5" class="form-control input-style2" id="message" placeholder="Your Message *" required data-validation-required-message="Please enter a message."></textarea>
              <p class="help-block text-danger"></p>
            </div>
            <div class="clearfix"></div>
            <div class="text-center">
              <div id="success"></div>
              <button id="sendMessageButton" class="btn btn-xl" type="submit">Send Message</button>
            </div>
            <!-- contact form ends -->

contact_me.js

$(function() {

  $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    },
    submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit behaviour
      // get values from FORM
      var name = $("input#name").val();
      var email = $("input#email").val();
      var phone = $("input#phone").val();
      var message = $("textarea#message").val();
      var firstName = name; // For Success/Failure Message
      // Check for white space in name for Success/Fail message
      if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
      }
      $this = $("#sendMessageButton");
      $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
      $.ajax({
        url: "././mail/contact_me.php",
        type: "POST",
        data: {
          name: name,
          phone: phone,
          email: email,
          message: message
        },
        cache: false,
        success: function() {
          // Success message
          $('#success').html("<div class='alert alert-success'>");
          $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-success')
            .append("<strong>Your message has been sent. </strong>");
          $('#success > .alert-success')
            .append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        error: function() {
          // Fail message
          $('#success').html("<div class='alert alert-danger'>");
          $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
          $('#success > .alert-danger').append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 1000);
        }
      });
    },
    filter: function() {
      return $(this).is(":visible");
    },
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});

PHP

<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.

"."Here are the details:

Name: $name

Email: $email_address

Phone: $phone

Message:
$message";
$headers = "From: noreply@yourdomain.com
"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

I am wondering do I need any configuration or something else to make mail() function work in my own website

</div>
  • 写回答

1条回答 默认 最新

  • doubao7287 2017-09-04 05:49
    关注

    Here are the areas I would look at first:

    Error Handling

    Currently, the script returns TRUE after the mail call, regardless of what the call does. The mail() method itself will return false if it fails, and there are ways to check the errors it might be throwing when it fails. Your $.ajax handler is always going to treat the call as "success" - because the call will always be returning TRUE. It may be better to assign the mail call to its own variable:

    $mail_succeeded = mail($to, $email_subject, $email_body, $headers);
    return $mail_succeeded;
    

    This will let you know if mail is actually functioning. The link above has examples of how to use this to also get associated error messages if they exist.

    Relative Path

    Have you double checked that your relative path is structured correctly to be handled as you expect by your web server? This may not be an issue, but the ././mail/contact_me.php caught my eye.

    (From a question regarding relative paths)

    The path segments "." and "..", also known as dot-segments, are defined for relative reference within the path name hierarchy. They are intended for use at the beginning of a relative-path reference (Section 4.2) to indicate relative position within the hierarchical tree of names. This is similar to their role within some operating systems' file directory structures to indicate the current directory and parent directory, respectively. However, unlike in a file system, these dot-segments are only interpreted within the URI path hierarchy and are removed as part of the resolution process (Section 5.2).

    Mail Settings on Server

    From the documentation for the theme you're using:

    If you're having trouble with the contact form, make sure to follow these steps:

    1. First make sure your website is hosted on a web server with PHP enabled. When the submit button is clicked, the PHP script in contact_me.php runs. If you're trying to use the form locally, the message wont send unless you have a server environment set up on your local machine.

    2. If you've uploaded your site to a web server and the form still isn't sending, there is probably a permissions/security issue preventing the form from sending email. First make sure that the email address that you're sending mail to is correct. If it's correct, try using an email address with a private domain, rather than something popular like Gmail or Yahoo. A lot of web hosts prevent forms from sending to popular mail servers for spam purposes. If it still isn't working after changing the email address, contact your web host to see if they can figure out what is preventing the form from sending.

    Along with this, you will need to make sure that you have your email settings defined and setup properly in your php.ini file. Your host may limit your options in terms of configurability, but here is a brief tutorial on setting this up.

    Check your PHP error log to make sure you're not missing something simple in the setup that is preventing the emails from sending.

    Finally, I'd urge you to avoid using PHP's mail() method for sending email. There are several well known exploits that make mail() a potentially insecure way to send email. There are other options that can be implemented very easily on your server to avoid the limitations and vulnerabilities of mail().

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

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3