Не удается отправить файл на почту
Делаю отправку формы на почту с прикреплением файла. Письмо приходит без файла. Помогите пожалуйста найти ошибку в коде.
файл mailsend.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require './php/vendor/autoload.php';
// Переменные, которые отправляет пользователь
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$file = $_FILES['userfile'];
$file_modal = $_FILES['userfile_modal'];
// Server side validation
function isValid() {
// This is the most basic validation for demo purpose. Replace this with your own server side validation
if($_POST['name'] != "" && $_POST['email'] != "" && $_POST['message'] != "") {
return true;
} else {
return false;
}
}
$error_output = '';
$success_output = '';
if(isValid()) {
// Build POST request to get the reCAPTCHA v3 score from Google
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6Leoa68ZAdfkfdkfjJJKKFCDVKSOVDATb3Ba'; // Insert your secret key here
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned
if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
// This is a human. Insert the message into database OR send a mail
//send a mail
// require_once "send.php";
$mail = new PHPMailer;
try {
$msg = "ok";
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->CharSet = "utf-8";
$mail->Host = 'smtp.beget.ru';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]'; // Ваш логин в Яндексе. Именно логин, без @yandex.ru
$mail->Password = '111111111'; // Ваш пароль
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]'); // Ваш Email
$mail->addAddress('[email protected]'); // Email получателя
// // Прикрипление файлов к письму
if (!empty($file['name'][0])) {
for ($ct = 0; $ct < count($file['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($file['name'][$ct]));
$filename = $file['name'][$ct];
if (move_uploaded_file($file['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
$rfile[] = "Файл $filename прикреплён";
} else {
$rfile[] = "Не удалось прикрепить файл $filename";
}
}
}
if (!empty($file_modal['name'][0])) {
for ($ct = 0; $ct < count($file_modal['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($file_modal['name'][$ct]));
$filename = $file_modal['name'][$ct];
if (move_uploaded_file($file_modal['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
$rfile[] = "Файл $filename прикреплён";
} else {
$rfile[] = "Не удалось прикрепить файл $filename";
}
}
}
$mail->isHTML(true);
$mail->Subject = 'Заявка с сайта';
$mail->Body = "<b> Имя: </b> $name <br/><b>Телефон:</b> $phone <br/></b><b>Почта:</b> $email <br/><b>Текст письма:</b> $message";
// Проверяем отравленность сообщения
if ($mail->send()) {
$success_output = "Your message sent successfully";
// echo "$msg";
} else {
$error_mail_output = "Сообщение не было отправленно, сервер не отвечает";
}
} catch (Exception $e) {
echo "Сообщение не было отправлено. Причина ошибки: {$mail->ErrorInfo}";
}
} else {
// Server side validation failed
$error_output = "Something went wrong. Please try again later";
}
} else {
$error_output = "Please fill all the required fields";
}
$output = array(
'error' => $error_output,
'success' => $success_output,
'error_mail' => $error_mail_output
);
// Output needs to be in JSON format
echo json_encode($output);
?>
form.php
<form class="form row" id="form" type="submit" method="post" enctype="multipart/form-data">
<div class="form__background"></div>
<h2 class="form__title text_title text_line col-lg-3">Оставьте заявку</h2>
<div class="w-100"></div>
<p class="form__comment text_main col-lg-7">и мы свяжемся с вами в ближайшее время. <br> Заполните опросный лист или оставьте контакты</p>
<div class="w-100"></div><a class="text_link link_accent text_main col" href="<?php bloginfo('template_url');?>/files/Пример технического задания.docx" download="">Скачать опросный лист</a>
<div class="w-100"></div>
<div class="form__row col-lg-6">
<input class="input form__input col form-control only_letters" placeholder="Имя*" name="name" required>
<input class="input form__input col form-control only_number" id="phone1" placeholder="Телефон*" type="tel" minlength="11" maxlength="11" name="phone" required><span class="text_main form__error">Это поле должно содержать 11-ти значный номер телефона</span>
<input class="input input__email form__input col form-control" id="inputEmail4" name="email" placeholder="Email" type="email" required><span class="text_main form__error">Это поле должно содержать E-Mail в формате [email protected]</span>
<div class="form__input form">
<div class="control-group">
<label class="control control-checkbox text_main text_mini label_whithe">Согласие на обработку персональных данных
<input class="control_indicator" type="checkbox" required>
<div class="control_indicator"></div>
</label>
</div>
</div>
</div>
<div class="form__row col-lg-6">
<textarea class="input__comment form__textarea input form__input col form__input_big form-control" type="text" name="message" placeholder="Комментарий*"></textarea>
<div class="input-file col text_main text_accent form__input input_accent">
<input class="inputfile" id="userfile" type="file" name="userfile[]" data-multiple-caption="{count} files selected" multiple="" accept="image/*">
<label class="text_accent text_mini" for="userfile"><span>Прикрепить файл</span></label>
</div>
<div class="alert" id="alert"></div>
<input id="recaptchaResponse" type="hidden" name="recaptcha_response">
<button class="button-send button-send_big form__button button-send_shadow col">Отправить заявку</button>
</div>
</form>
файл form.js
$('#form').submit(function(event) {
event.preventDefault(); // Prevent direct form submission
$('#alert').text('Processing...').fadeIn(0); // Display "Processing" to let the user know that the form is being submitted
grecaptcha.ready(function () {
console.log('i am redy ');
grecaptcha.execute('6Leoa68ZAAAAAFhrhHXVIqwkRq9HMQ_acuTY9ZbG', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
$.ajax({
url: 'https://prointechnology.ru/wp-content/themes/prointex/mailsend.php',
type: 'post',
data: $('#form').serialize(),
dataType: 'json',
success: function( _response ){
// The Ajax request is a success. _response is a JSON object
var error = _response.error;
var success = _response.success;
if(error != "") {
// In case of error, display it to user
$('#alert').html(error);
}
else {
$(".form").trigger("reset"); // очистка формы
$(".close").parents(".popup-fade");
$(".popup-fade").removeClass("popup-fade-show");
$(".popup-fade-secces").addClass("popup-fade-show");
// In case of success, display it to user and remove the submit button
$('#alert').html(success);
// $('#submit-button').remove();
}
},
error: function(jqXhr, json, errorThrown){
// In case of Ajax error too, display the result
var error = jqXhr.responseText;
$('#alert').html(error);
}
});
});
});
});