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.
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. 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.
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". 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.
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!";
}
}
}
?>