【问题标题】:Send Email with php with html form data使用带有 html 表单数据的 php 发送电子邮件
【发布时间】:2020-02-05 10:12:48
【问题描述】:

我不知道 php 是如何工作的。我对每个逻辑都使用 JavaScript,但它仅供客户端使用,而我认为 php 用于服务器。我收到 405(不允许的方法)错误。

如何使用来自 html 表单的输入数据向自己发送电子邮件(例如:“example@gmail.com”)?

//** IF u need it **

// Working Contact Form
$('#contact-form').submit(function() {
  var action = $(this).attr('action');

  $("#message").slideUp(750, function() {
    $('#message').hide();

    $('#submit').before('').attr('disabled', 'disabled');

    $.post(action, {
        name: $('#name').val(),
        email: $('#email').val(),
        comments: $('#comments').val(),
      },
      function(data) {
        document.getElementById('message').innerHTML = data;
        $('#message').slideDown('slow');
        $('#cform img.contact-loader').fadeOut('slow', function() {
          $(this).remove()
        });
        $('#submit').removeAttr('disabled');
        if (data.match('success') != null) $('#cform').slideUp('slow');
      }
    );

  });

  return false;

});

// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict'
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation')

    // Loop over them and prevent submission
    Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        console.log("test")
        if (form.checkValidity() === false) {
          event.preventDefault()
          event.stopPropagation()
        }
        form.classList.add('was-validated')
      }, false)
    })
  }, false)
}())
//Ignore CSS, doesnt matter
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="php/contact.php" name="contact-form" id="contact-form">
  <div class="row">
    <div class="col-lg-6">
      <div class="row">
        <div class="col-lg-12 col-md-6">
          <div class="form-group">
            <input name="name" id="name" type="text" class="form-control border rounded" placeholder="Name :">
          </div>
        </div>
        <!--end col-->
        <div class="col-lg-12 col-md-6">
          <div class="form-group">
            <input name="email" id="email" type="email" class="form-control border rounded" placeholder="Email :">
          </div>
        </div>
        <!--end col-->
        <div class="col-lg-12">
          <div class="form-group">
            <input name="subject" id="subject" class="form-control border rounded" placeholder="Betreff :">
          </div>
        </div>
        <!--end col-->
      </div>
      <!--end row-->
    </div>
    <!--end col-->

    <div class="col-lg-6">
      <div class="form-group">
        <textarea name="comments" id="comments" rows="4" class="form-control border rounded" placeholder="Nachricht :"></textarea>
      </div>
    </div>
    <!--end col-->
  </div>
  <!--end row-->
  <div class="row">
    <div class="col-sm-12 text-right">
      <input type="submit" id="submit" name="send" class="submitBnt btn btn-pill btn-custom" value="Senden">
      <div id="simple-msg"></div>
    </div>
    <!--end col-->
  </div>
  <!--end row-->
</form>
<!--end form-->

我正在使用带有 LiveServer 扩展的 VS-Code 来创建网站。我可以在那里使用 php 还是有什么问题?顺便说一句,我认为 JS 仍然有问题..?!

如果有人知道如何提供帮助,请发表评论!谢谢。

【问题讨论】:

  • @MarkOverton 不,它没有。我已经看过这个帖子了。我的问题是,我收到 405(不允许的方法)错误,我不知道如何解决。
  • 那么你发送$.post请求的地址不允许POST方法。而是尝试GET 方法,或允许POST。但是,如果我们不能查看您的 PHP,就很难看到发生了什么。
  • @EmielZuurbier 谢谢你的提示。问题是,我以前从未使用过 php。我不知道如何使用它,但在他们说的其他一些 stackoverflow.com 网站上,我可以使用它:&lt;?php $to = 'test@gmail.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?&gt; 这就是我添加 js 的原因,以便您可以告诉我如何正确编写它。

标签: javascript php html forms


【解决方案1】:

每个.php 文件都使用&lt;?php 关键字打开。它表明该文件包含 PHP 代码。 HTML 可以在 PHP 文件中使用,因此没有不同的文件类型。用?&gt;关闭php文件。

您也可以在 HTML 中包含单行 PHP 代码。

<?php $title = 'Hello World'; ?>
<h1><?php echo $title; ?></h1>

您需要收集发送到服务器的数据。 PHP 有全局变量,它们是在任何文件中随处可用的变量。例如$_GET 变量。如果您使用GET 方法发送数据,那么您将能够读取从您发送到的文件中的全局$_GET 变量中的数据。

$_GET 是一个associative array。所以发送的数据是这样存储的:

[
  'name' => '',
  'email' => '',
  'comments' => ''
]

关联数组类似于 JavaScript 中的对象。它们都有一个键和一个值。检查是否使用 PHP 中的isset() 函数设置了密钥。

因为您允许用户发送数据,所以清理他们的数据很重要。它可能包含恶意代码,在您清理它之前应该被视为恶意代码。 filter_var 是一个 PHP 函数,它可以为你做到这一点。

现在您已经拥有并清理了数据,您可以使用mail 函数向电子邮件地址发送邮件。 mail 函数根据邮件是否发送成功返回一个布尔值。

祝你好运!

<?php

/** 
 * Get all the send data from JS.
 * $_GET is a global PHP variable. It is an array
 * which contains the data sent with the GET method.
 */
$name     = isset($_GET['name']) ? $_GET['name'] : '';
$email    = isset($_GET['email']) ? $_GET['email'] : '';
$comments = isset($_GET['comments']) ? $_GET['comments'] : '';

/**
 * All data that a user can send must be treated as dirty.
 * Therefor it is important to filter all malicious characters
 * from the data. Otherwise you are open to vulnerabilities.
 */
$name     = filter_var($name, FILTER_SANITIZE_STRING);
$email    = filter_var($email, FILTER_SANITIZE_EMAIL);
$comments = filter_var($comments, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

/**
 * Now the data is received and sanitized we can use it
 * to send an email with.
 */
$to      = $email; // The email address to send to.
$from    = 'sender@example.com'; // Your email address.
$subject = 'the subject'; 
$message = $comments; // I assume comments is the message. 
$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion(); 

/**
 * Send the email.
 * The mail() function returns a true or false based
 * on if the email was sent successfully.
 */
$mail_status = mail($to, $subject, $message, $headers);

/**
 * Send a message back to JS based on if the mail has beent sent or not.
 */
if ($mail_status === true) {
  return 'Mail has been sent';
} else {
  return 'Sending the mail has failed';
}

?>

【讨论】:

  • 要补充一点。我仍然在控制台输出中收到 405(不允许的方法)错误。这是一个错误,因为我使用的是 VS Code Live Server 还是我必须如何处理这个错误?
  • 不,这是因为你使用了$.post,顾名思义,它使用POST 方法将数据从JS 发送到PHP。请改用 GET 的等效 jQuery 函数。它甚至可能被称为$.get ;)
  • 我将$.post 更改为$.get,但它仍然不起作用。我没有收到任何电子邮件。错误消息不再存在,所以我认为这很好,现在我在 vs-code 中收到了另一个通知:live reload is not possible without body or head tag
  • 好吧,你必须在某种服务器上运行 PHP。可以是本地的或托管的。研究如何设置您的 PHP 服务器。实时重新加载是不够的。
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2020-06-12
  • 1970-01-01
  • 2020-04-22
  • 2016-03-11
相关资源
最近更新 更多