Answer the question
In order to leave comments, you need to log in
How to make PHPmailer and reCAPTCHA friends?
There is a form that is connected to the send.php file.
The code without captcha looks like this:
<?php
// Файлы phpmailer
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
require 'phpmailer/Exception.php';
// Переменные, которые отправляет пользователь
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$file = $_FILES['myfile'];
// Формирование самого письма
$title = "Заголовок письма";
$body = "
<h2>Новое письмо</h2>
<b>Имя:</b> $name<br>
<b>Почта:</b> $email<br><br>
<b>Сообщение:</b><br>$text
";
// Настройки PHPMailer
$mail = new PHPMailer\PHPMailer\PHPMailer();
try {
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Debugoutput = function($str, $level) {$GLOBALS['status'][] = $str;};
// Настройки вашей почты
$mail->Host = 'smtp.yandex.ru'; // SMTP сервера вашей почты
$mail->Username = 'yandex'; // Логин на почте
$mail->Password = '*******'; // Пароль на почте
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Заявка с сайта!'); // Адрес самой почты и имя отправителя
// Получатель письма
$mail->addAddress('[email protected]');
// Прикрипление файлов к письму
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";
}
}
}
// Отправка сообщения
$mail->isHTML(true);
$mail->Subject = $title;
$mail->Body = $body;
// Проверяем отравленность сообщения
if ($mail->send()) {$result = "success";}
else {$result = "error";}
} catch (Exception $e) {
$result = "error";
$status = "Сообщение не было отправлено. Причина ошибки: {$mail->ErrorInfo}";
}
// Отображение результата
echo json_encode(["result" => $result, "resultfile" => $rfile, "status" => $status]);
?>
<?php
$captcha;
if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
$secretKey = "********************";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['token'];
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"] && $responseKeys["score"] >= 0.5) {
echo json_encode(array('success' => 'true', 'om_score' => $responseKeys["score"], 'token' => $_POST['token']));
} else {
echo json_encode(array('success' => 'false', 'om_score' => $responseKeys["score"], 'token' => $_POST['token']));
}
?>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question