S
S
Sasha5452020-08-10 16:55:25
PHP
Sasha545, 2020-08-10 16:55:25

How to add a server mailbox to PhpMailer?

Good afternoon! phpmailer form. I did everything according to the "instructions". The message does not come to Yandex in its entirety, only the mail address and name. The author of the form writes that the form checks the mail for validity, while "pieces" of letters come even if a set of random characters is specified in the email field. And when checking with developer, an html error was found, .file-wrap block cannot be a child of . 3 php files did not change. I read that you need to specify the host's email address.

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <title>PHPMAILER</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:[email protected];500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles/style.css" />
    <script src="js/gsap.min.js"></script>
    <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
      <div class="msg" onclick="gsapMsg.reverse()">Сообщение
      </div>
    <div class="wrap">
    <form enctype="multipart/form-data" method="post" id="form" onsubmit="send(event, 'send.php')">
    <div class="group-input">
    <div class="group-text-input">
    <div class="input-wrap">
        <input name="name" id="name" type="text" class="form-input aInput" autocomplete="off">
         <label for="name" class="input-label">Представьтесь</label>
    </div>
    <div class="input-wrap">
        <input name="email" id="email" type="text" class="form-input aInput" autocomplete="off">
        <label for="email" class="input-label">Укажите почту</label>
    </div>
    </div>
    <div class="input-wrap">
 	    <textarea name="texta" id="texta" class="aInput"></textarea>
        <label for="texta" class="area-label">Сообщение</label>
    </div>
    </div>
    <div class="file-wrap">
        <label for="myfile" class="labelFile">
            <img src="https://img.icons8.com/ios/50/000000/upload-to-cloud.png" alt="img"/>
            <p class="count">Прикрепить файлы</p>
        </label>
        <input type="file" multiple class="inputFile" id="myfile" name="file[]" onchange="inputFile(event)" />
    </div>
    <button type="submit" class="button right">Отправить</button>
    </form>
    	</div>
</body>
<script src="js/script.js"></script>
</html>

script.js
// Объявления
var msg = document.querySelector(".msg");
var gsapMsg = gsap.to(".msg", 0.25, {autoAlpha: 1,y: -40,ease: Expo.inOut, paused: true});
var arrInput = document.querySelectorAll('.aInput');

// Функция отправки сообщения
function send(event, php){
event.preventDefault ? event.preventDefault() : event.returnValue = false;
for (var i = 0,count=arrInput.length; i<count; i++) {arrInput[i].classList.remove("errorInput");}
event.target.querySelector("button").disabled = true;
showMsg("Подождите. Идёт отправка сообщения", "#b1b1b1");
var req = new XMLHttpRequest();
req.open('POST', php, true);
req.onload = function() {
event.target.querySelector("button").disabled = false;
    if (req.status >= 200 && req.status < 400) {
        json = JSON.parse(this.response); //  internet explorer 11
        console.log(json);

        // ЗДЕСЬ УКАЗЫВАЕМ ДЕЙСТВИЯ В СЛУЧАЕ УСПЕХА ИЛИ НЕУДАЧИ
        if (json.result == "success") {
            // если сообщение отправлено
            showMsg("Сообщение успешно отправлено", "#36AE46");
            console.log("Сообщение отправлено");
            event.target.reset();
        } else if(json.result == "email") {
            // Если указан неверный email
            showMsg("Ошибка. Неверно указан Email", "#DC352F");
            console.log("Ошибка. Неверно указан Email");
            document.querySelector("#email").classList.add("inputerror");
        } else {
            // Если произошла ошибка
            showMsg("Ошибка. Сообщение не отправлено", "#DC352F");
            console.log("Ошибка. Сообщение не отправлено");
        }

    // Если не удалось связаться с php файлом
    } else {showMsg("Ошибка сервера. Номер: "+req.status, "#DC352F");}}; 

// Если не удалось отправить запрос. Стоит блок на хостинге
req.onerror = function() {showMsg("Ошибка отправки запроса", "#DC352F");};
req.send(new FormData(event.target));
}

// Функция появления статуса отправки сообщения
function showMsg(message, color) {
msg.innerText = message;
msg.style.background = color;
gsapMsg.restart();
}

// Оформление input file
function inputFile(e) {
    el = e.target.parentNode.querySelector(".count");
    if (e.target.value != '') el.innerHTML = "Выбрано файлов: " + e.target.files.length;
    else el.innerHTML = 'Прикрепить файлы';
}

// Анимация input text
for (var i = 0, count = arrInput.length; i < count; i++) {
arrInput[i].addEventListener("focus", function() {
this.nextElementSibling.classList.add("active");
});
arrInput[i].addEventListener("blur", function() {
if (this.value == false) 
this.nextElementSibling.classList.remove("active");
});
}

// Анимация появления блоков
window.onload = function() {
var loadPage = gsap.timeline();
loadPage.to("#form", 0.7, {autoAlpha: 1,y: 0, ease: Expo.inOut});
loadPage.to(".link", 0.7, {autoAlpha: 1,y: 0, ease: Expo.inOut}, 0);
loadPage.to(".input-wrap", 0.5, {stagger: 0.15, autoAlpha: 1,y: 0, ease: Expo.inOut}, 0.35);
loadPage.to(".file-wrap, .button", 0.5, {stagger: 0.15, autoAlpha: 1,x: 0, ease: Expo.inOut}, 0.6);
}

send.php
<?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   = 'Xxxx'; // Пароль на почте
$mail->SMTPSecure = 'ssl';
$mail->Port       = 465;
$mail->setFrom('логин@yandex.ru', 'Александр');
    // Получатель письма
    $mail->addAddress('логин@yandex.ru');  
   
     // Прикрипление файлов к письму
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]);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question