javascript - PHP 表单发送正确,但我没有收到电子邮件

标签 javascript php ajax email

我正在尝试通过此引导模板创建 PHP 联系表单: https://startbootstrap.com/template-overviews/agency/

此模板可以在我的本地主机中找到,电子邮件正确发送,我收到了电子邮件。

但是当我在自己的网站上使用他们的代码时,它总是说电子邮件正确发送,但我从未收到电子邮件

下面是代码

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.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // 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;
?>

我想知道我是否需要任何配置或其他东西才能使 mail() 函数在我自己的网站中工作

最佳答案

以下是我首先关注的领域:

错误处理

目前,无论调用执行什么操作,脚本都会在邮件调用后返回 TRUE。如果失败,mail() 方法本身将返回 false,并且 there are ways to check the errors it might be throwing当它失败时。您的 $.ajax 处理程序始终将调用视为“成功” - 因为调用始终返回 TRUE。将 mail 调用分配给它自己的变量可能会更好:

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

这会让您知道邮件是否确实正常运行。上面的链接提供了如何使用它来获取关联的错误消息(如果存在)的示例。

相对路径

您是否仔细检查过您的相对路径结构是否正确,以便您的网络服务器按照您的预期进行处理?这可能不是问题,但 ././mail/contact_me.php 引起了我的注意。

(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).

服务器上的邮件设置

来自您正在使用的主题的文档:

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.

除此之外,您还需要确保在 php.ini 文件中正确定义和设置了电子邮件设置。 您的主机可能会在可配置性方面限制您的选项,但是here is a brief tutorial关于设置。

检查您的 PHP 错误日志,确保您在设置中没有遗漏一些阻止电子邮件发送的简单内容。

最后,我强烈建议您避免使用 PHP 的 mail() 方法发送电子邮件。有several well known exploits这使得 mail() 成为一种潜在不安全的发送电子邮件方式。还有其他选项可以在您的服务器上轻松实现,以避免 mail() 的限制和漏洞。

关于javascript - PHP 表单发送正确,但我没有收到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46030317/

相关文章:

javascript - ui-bootstrap 下拉菜单中每行两个元素

javascript - 在 AngularJS 中添加 ng-switch 后,滚动事件未绑定(bind)到 html 元素

javascript - 如何仅更改 1 行而非全部的切换值

javascript - 使用 Javascript 获取 URL 参数

php - 在 Active Collab API 中获取分页结果

php - mysqli connect() 使用 IP 地址时收到错误消息

javascript - 如果 URL 有 "just one HTML line",jQuery.load() 为什么可以跨域工作?

php - 使用之间的差异?和 :param in prepare statement

java - [t5.2.6]在循环内生成区域,然后更新其中的一些区域

javascript - AngularJS 上不断出现注入(inject) modulerr 错误