简体   繁体   English

使用提取将JavaScript数组转换为PHP,然后发送电子邮件

[英]Converting JavaScript array to PHP using fetch and then sending email

I'm struggling trying to convert my JavaScript array of emails into a PHP array which I can then send an email back to using my localhost. 我正在努力将JavaScript的电子邮件数组转换为PHP数组,然后可以使用本地主机将电子邮件发送回。

I have an input field in my html that is populated by the user (one at a time) which uses .push in JavaScript to put them into the array. 我在html中有一个由用户填充的输入字段(一次填充一个),该字段在JavaScript中使用.push将其放入数组中。 I have tried to use fetch to then convert this array into PHP, which I can then then use to send an email back to the email addresses using PHPMailer. 我试图使用fetch将数组转换为PHP,然后可以使用PHPMailer将其发送回电子邮件地址。

The emails aren't appearing in my console as an array, but will do if I change the content type to "Content-Type": "application/x-www-form-urlencoded". 这些电子邮件未在我的控制台中显示为数组,但是如果我将内容类型更改为“ Content-Type”:“ application / x-www-form-urlencoded”,则可以。 However, the emails still aren't being sent this way. 但是,仍然没有以这种方式发送电子邮件。

This is only for a small uni project, that's why I am only concerned about sending the emails through my localhost as I won't be hosting the project anywhere. 这仅适用于小型uni项目,这就是为什么我只关心通过本地主机发送电子邮件的原因,因为我不会在任何地方托管该项目。

HTML: HTML:

<input type="text" id="names" placeholder="Name" />
<input type="text" id="emails" placeholder="Email address" />
<input type="button" onclick="addTo()" value="Add" />

<input type="button" id="done-button" onclick="completed()" value="Done" />

JavaScript: JavaScript的:

var names = [];
var emails = [];
var allNumbers = [];

function addTo() {
    names.push(document.getElementById("names").value);
    document.getElementById("names").value = "";
    emails.push(document.getElementById("emails").value);
    document.getElementById("emails").value = ""; 
}

function completed() {
    var numbers = names.length;
        for (var i = 1; i <= numbers; i++) {
            allNumbers.push(i);
        }

    fetch("http://localhost:8888/fetchme.php", {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "no-cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json"
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: emails // body data type must match "Content-Type" header
    }).then((response) => {console.log(response)}); // parses response to console
}

PHP: PHP:

<?php 
var_dump($_POST);

use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "example@gmail.com";
$mail->Password = "password";
$mail->setFrom('example@gmail.com', 'Example');

$emails = json_decode($_POST);

if (isset($emails)) {
    foreach ($emails as $email) {
        $mail->addAddress($email);
        $mail->Subject = 'Your Results';
        //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('index.html'), __DIR__);
        $mail->Body = 'Hello, this is my message.';
        $mail->AltBody = 'This is a plain-text message body';
        if (!$mail->send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message sent!";
        }
    }
}
?>

Using fetch() with an array as body doesn't send a JSON string. fetch()与数组一起用作正文不会发送JSON字符串。 What's being sent to the server is a comma separated list of the email addresses. 发送到服务器的是电子邮件地址的逗号分隔列表。 Anyway, PHP won't put them into $_POST because the body is not a valid query string. 无论如何,PHP不会将它们放入$_POST因为主体不是有效的查询字符串。

First, you should use JSON.stringify() to convert the emails array to a JSON string. 首先,您应该使用JSON.stringify()emails数组转换为JSON字符串。 Then, in PHP, you could read the request body with http_get_request_body() . 然后,在PHP中,您可以使用http_get_request_body()读取请求正文。

Or, you can build the query string to set it as the body of the request, and then you'll be able to use $_POST normally. 或者,您可以构建查询字符串以将其设置为请求的正文,然后可以正常使用$_POST

尝试使用而不是id来命名和发送电子邮件,然后尝试通过控制台日志在javascript本身中获取价值,如果要在将javascript传递给PHP之前获得价值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM