javascript - 无法将 jquery 数据 POST 到 phpmailer

标签 javascript php phpmailer

HTML 形式:

<form id="contacts-form">
  <input name="email" type="text">
  <textarea name="contacts-form-textarea"></textarea>
  <button type="submit">Send</button>
</form>

JS:

var $form = $("#contacts-form");
$form.on("submit", submitHandler);

function submitHandler(e) {
  e.preventDefault();
  $.ajax({
    url: '/sendmail2.php',
    type: 'POST',
    data: $form.serialize()
  }).done(response => {
    if (JSON.parse(response).success) {
      console.log('success');
      $form.trigger('reset');
    } else {
      console.log('fail');
    }
  });
}

sendmail2.php(基本上是official phpmailer example for gmail,稍作修改):

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;

// require '../vendor/autoload.php';
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "myemail@gmail.com";

//Password to use for SMTP authentication
$mail->Password = "mypass";

//Set who the message is to be sent from
$mail->setFrom('from@example.com', 'First Last');

//Set an alternative reply-to address
$mail->addReplyTo('replyto@example.com', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('anotherone@gmail.com', 'My Name');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
// $mail->msgHTML(file_get_contents('contentss.html'), __DIR__);
$mail->msgHTML('<h1>' . $_POST["email"] . '</h1>');

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
// $mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    // echo "Mailer Error: " . $mail->ErrorInfo;
    $results = array('success' => false);
    echo json_encode($results);
} else {
    // echo "Message sent!";
    $results = array('success' => true);
    echo json_encode($results);
    //Section 2: IMAP
    //Uncomment these to save your message in the 'Sent Mail' folder.
    #if (save_mail($mail)) {
    #    echo "Message saved!";
    #}
}

//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
    //You can change 'Sent Mail' to any other folder or tag
    $path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";

    //Tell your server to open an IMAP connection using the same username and password as you used for SMTP
    $imapStream = imap_open($path, $mail->Username, $mail->Password);

    $result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
    imap_close($imapStream);

    return $result;
}

邮件发送按预期进行,我在电子邮件中收到了该消息。但由于某种原因,数据没有发送到sendmail2.php

当我 console.log JS 文件中的数据时,它工作正常,但后端的 $_POST["email"] 返回 null。我试过了

var data = {
  email: $("#contacts-form input").val()
};

在我的 JS 中,也不起作用。

最佳答案

在 POST 中,对象包含在 data 属性中。因此,您可能必须通过以下方式访问 PHP 文件中的数据:

$_POST['data'];

因为它是一个对象,所以你必须解码

$data = json_decode( $_POST['data'], true);

然后使用;

访问它
$data['email'];

请确保您的 ajax 中的数据属性格式如下;

data: { 'email':'test@test.com' }

关于javascript - 无法将 jquery 数据 POST 到 phpmailer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52618266/

相关文章:

javascript - 单击后隐藏复选框

javascript - 选中该字段的复选框时设置 Attr Required

javascript - 在 div 中相对于 div 定位图像

javascript - 在 moment.js 中本地化日和月

PHP 域可用性脚本 exec() 函数替代

PhpMailer:加载一段时间然后 ERR_EMPTY_RESPONSE

php - 作为垃圾邮件发送的帐户确认电子邮件

php - 在 phpmailer 中设置紧急选项

javascript - CORS 错误仅对 400 个错误请求使用react获取请求

php - 断句的 css 属性