【发布时间】:2019-05-28 02:04:02
【问题描述】:
我正在努力尝试将我的 JavaScript 电子邮件数组转换为 PHP 数组,然后我可以使用本地主机将电子邮件发送回。
我的 html 中有一个输入字段,由用户(一次一个)填充,它使用 JavaScript 中的 .push 将它们放入数组中。我尝试使用 fetch 将此数组转换为 PHP,然后我可以使用 PHPMailer 将电子邮件发送回电子邮件地址。
电子邮件不会以数组的形式出现在我的控制台中,但如果我将内容类型更改为“Content-Type”:“application/x-www-form-urlencoded”就会出现。但是,电子邮件仍然没有以这种方式发送。
这仅适用于一个小型 uni 项目,这就是为什么我只关心通过本地主机发送电子邮件,因为我不会在任何地方托管该项目。
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:
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
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!";
}
}
}
?>
【问题讨论】:
-
exit在它运行后停止任何东西。 -
如果您在正文中以 json 格式发布数据,您可能需要使用
$json = file_get_contents('php://input');获取它。你可以阅读更多关于区别here -
$emails = json_decode($_POST);毫无意义。通常的方法见@MagnusEriksson 评论。
标签: javascript php arrays localhost fetch