Answer the question
In order to leave comments, you need to log in
How to connect React form to PHPMailer?
Greetings) I can’t connect a feedback form made on React to PHPMailer ... I don’t know PHP and server languages at all, I need to somehow connect this feedback form. The site is uploaded to free hosting ru.000webhost.com. Or maybe there are some other connection options .....? (NOT google forms) How do you include forms in React?
React (Form.js)
import React, { Component } from "react";
import mod from "./Form.module.sass";
class Form extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
text: "",
myfile: ""
};
}
Change(e) {
const { id, value } = e.currentTarget;
this.setState({ [id]: value });
}
onSubmit(e) {
e.preventDefault();
let formData = new FormData();
if (this.state.myfile) {
formData.append("myfile", this.state.myfile);
}
formData.append("name", this.state.name);
formData.append("email", this.state.email);
formData.append("text", this.state.text);
fetch("send.php", {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data"
}
}).then(response => {
response.json().then(data => {
console.log("Successful" + data);
});
});
}
render() {
const { name, email, text } = this.state;
return (
<form
id="form"
encType="multipart/form-data"
method="post"
className={mod.form}
onSubmit={this.onSubmit.bind(this)}
>
<p>Имя</p>
<input
id="name"
name="name"
type="text"
value={name}
placeholder="Представьтесь"
onChange={this.Change.bind(this)}
/>
<p>Email</p>
<input
id="email"
name="email"
type="text"
value={email}
placeholder="Укажите почту"
onChange={this.Change.bind(this)}
/>
<p>Сообщение</p>
<textarea
id="text"
name="text"
value={text}
onChange={this.Change.bind(this)}
/>
<p>Прикрепить файлы</p>
<input
id="myfile"
type="file"
name="myfile[]"
multiple
onChange={this.Change.bind(this)}
/>
<p>
<input value="Отправить" type="submit" />
</p>
</form>
);
}
}
export default Form;
<?php
// Файлы phpmailer
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
require 'phpmailer/Exception.php';
// Переменные, которые отправляет пользователь
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$mail = new PHPMailer\PHPMailer\PHPMailer();
try {
$msg = "ok";
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
// Настройки вашей почты
$mail->Host = 'smtp.gmail.com'; // SMTP сервера GMAIL
$mail->Username = 'login'; // Логин на почте
$mail->Password = '*******'; // Пароль на почте
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Alina'); // Адрес самой почты и имя отправителя
// Получатель письма
$mail->addAddress('[email protected]');
$mail->addAddress('[email protected]'); // Ещё один, если нужен
// Прикрипление файлов к письму
if (!empty($_FILES['myfile']['name'][0])) {
for ($ct = 0; $ct < count($_FILES['myfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['myfile']['name'][$ct]));
$filename = $_FILES['myfile']['name'][$ct];
if (move_uploaded_file($_FILES['myfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Неудалось прикрепить файл ' . $uploadfile;
}
}
}
// -----------------------
// Само письмо
// -----------------------
$mail->isHTML(true);
$mail->Subject = 'Заголовок письма';
$mail->Body = "<b>Имя:</b> $name <br>
<b>Почта:</b> $email<br><br>
<b>Сообщение:</b><br>$text";
// Проверяем отравленность сообщения
if ($mail->send()) {
echo "$msg";
} else {
echo "Сообщение не было отправлено. Неверно указаны настройки вашей почты";
}
} catch (Exception $e) {
echo "Сообщение не было отправлено. Причина ошибки: {$mail->ErrorInfo}";
}
Answer the question
In order to leave comments, you need to log in
When loading the page in the console this messagesome resource, image or font just didn’t load, see the details in the network.
After filling out and submitting the form in the console, this is
...
In the Network tab, this is
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question