如何使用AJAX提交的$_POST数据发送电子邮件

How to send an email with $_POST data submitted with AJAX

本文关键字:数据 POST 电子邮件 何使用 AJAX 提交      更新时间:2023-09-26

我想提交一些数据从localStorage到

Autoform.submitStoredData = function() {
    var data = localStorage.tbRecoveredData;
    if(data) {
        jQuery.ajax ({
            type: "POST",
            url:"http://www.thewebsite.com/Autoform.php",
            data: data,
            success: function() {
                console.log("success");
            },
            error: function(xhr,status,error) {
                console.log("payload failed to submit with xhr: " + xhr + ", status: " + status + ", and error: " + error);
            }
        });
        localStorage.removeItem("tbRecoveredData");
    }
};

到目前为止,我在控制台获得了"成功"。Autoform PHP看起来像这样:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = $_POST;
        mail('myemail@gmail.com', 'OK SO here at least is the captured string', $data);
    }
?>

这没有做任何事情,或者至少没有发送电子邮件。我承认我对PHP了解不多,我试过用google搜索,但运气不好。我是否需要将其包装在一种自调用函数或其他东西中,因为PHP代码似乎没有被执行。任何帮助都很感激,谢谢!

好的,如果你试着输入下面的代码并发现它是NULL:

var_dump(mail(...));

然后你需要配置你的服务器,使PHP工作与它的内置mail()函数。有几种方法可以做到这一点:

  • PHP mail() function enable
  • PHP邮件配置如何配置PHP发送电子邮件?

如果你想发送一个电子邮件你的函数mail()。必须进行配置。就像上面的答案。所以我建议你用SMTP发送邮件。无需配置即可轻松发送。你只需要注册一个私人邮箱,如email或Yahoo。

From this Question

  // Pear Mail Library    require_once "Mail.php";
  $from = '<your@mail.com>'; //change this to your email address  $to =
'<someone@mail.com>'; // change to address    $subject = 'Insert subject
here'; // subject of mail     $body = "Hello world! this is the content
of the email"; //content of mail
  $headers = array(
      'From' => $from,
      'To' => $to,
      'Subject' => $subject   );

  $smtp = Mail::factory('smtp', array(
          'host' => 'ssl://smtp.gmail.com',
          'port' => '465',
          'auth' => true,
          'username' => 'your@gmail.com', //your gmail account
          'password' => 'snip' // your password
      ));
    // Send the mail  $mail = $smtp->send($to, $headers, $body);