W
W
Web Building2020-12-04 20:31:40
PHPMailer
Web Building, 2020-12-04 20:31:40

HTML form is sent by ajax, but data from HTML form is not sent to Email. There are no errors anywhere. What is the problem?

Installed PHPMailer via Composer on hosting. There are no errors either in the ChromeDevTools console or in the logs...
And the letters do not come to Email: neither only text, nor text with attached files!
Here is the location of the files and folders relevant to the problem:

/home/homexnmx/vendor/autoload.php
The vendor folder consists of folders:
- composer with files inside
- phpmailer / phpmailer with folders and files inside;
- autoload.php /home/homexnmx/composer.json/home/homexnmx/composer.lock/home/homexnmx/public_html/composer.phar

-
(
used to be here)
/ home / homexnmx / composer.phar / public_html - (now moved here, but it did not play any role)
/ home / homexnmx / public_html / php.ini
/ home / homexnmx / public_html / tmp_name/ uploads - (uploads - for uploading files from form)
/home/homexnmx/public_html/tmp_name/submit.php - (submit.php - HTML form handler)
/home/homexnmx/public_html/php/httpd.conf - (php_value include_path ".:/opt/alt/ php72/usr/share/pear";)
/home/homexnmx/public_html/adaptive.php - (html form) /home/homexnmx/public_html/js/adaptive.js - (html form
submit js code)

Here is the handler submit.php

use PHPMailer\PHPMailer\PHPMailer;   // создайте класс PHPMailer
            use PHPMailer\PHPMailer\SMTP;
            use PHPMailer\PHPMailer\Exception;    
            
            require '/home/homexnmx/vendor/autoload.php'; 
            
            function sendmail($to, $nameto, $subject, $message, $file)  {
               $from  = "отправитель@gmail.com";  // адрес отправителя
               $namefrom = "Webbuilding";  // имя отправителя
               $mail = new PHPMailer();
               $mail->SMTPDebug = 0;
               $mail->CharSet = 'UTF-8';
               $mail->isSMTP();
               $mail->SMTPAuth   = true;
               $mail->Host   = "smtp.gmail.com";
               $mail->Port       = 465;
               $mail->Username   = $from;
               $mail->Password   = "******"; // пароль Email отправителя
               $mail->SMTPSecure = "ssl";
               $mail->setFrom($from, $namefrom);
               $mail->addCC($from, $namefrom);
               $subject = 'Из модальной формы - adaptive.php';
               $mail->Subject  = $subject;
               $mail->isHTML();
               $message = "Имя:  ".$_POST['user_name']."\r\nEmail:  ".$from."\r\nWebsite:  ".$_POST['user_website']."\r\nPhone:  ".$_POST['user_phone']."\r\nIP:  ".$_SERVER['REMOTE_ADDR']."\r\n\r\n Сообщение:\r\n\r\n   ".$_POST['user_comment'];
               $mail->Body = $message;
               
                  // Прикрипление файлов к письму
            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->AltBody  = $file;
               
               $to = 'получатель@mail.com'; // адрес получателя
               $nameto = 'Homexnmx';  // имя получателя
               $mail->addAddress($to, $nameto);
                //return $mail->send();
                  
                if ( $mail->send() ) {
                   echo $resalt = '<b>Your message sent!</b><br><br><pre><b> <a href="https://site.com" style="text-decoration:none;"> ⬅ Back to page</a></b></pre>';
                }
                
                else {
                   echo $resalt = 'Mailer Error';  
                } 
                  
            }


And here is adaptive.js form submit Ajax

var resalt = document.querySelector('.resalt'); 
        
            $("#modal-form").submit(function(e){
                e.preventDefault();
                if(document.getElementById('modal-form').user_name.value == '' || document.getElementById('modal-form').user_email.value == '' || document.getElementById('modal-form').user_website.value == '' || document.getElementById('modal-form').user_phone.value == ''){
                    valid = false;
                    return valid;
                }
                $.ajax({
                    type: "POST",
                    url: "https://site.com/tmp_name/submit.php",
                    data: $(this).serialize(),
                    success: function(data){
                        
                        resalt = '<b>JS Your message sent!</b>';  
                        
                        $('.block-popup').hide('');
                        $('.note').css('display', 'block');
                        $('.resalt').html(data);
                    },
                    error: function(jqXHR, exception) {
                        console.log(jqXHR);
                        console.log(exception);
                        
                        resalt = 'Mailer Error'; 
                        
                        $('.block-popup').hide('');
                        $('.note').css('display', 'block');
                        $('.resalt').html(data);
                    }
                });
                return;
            });


And here is the HTML form itself, adaptive.php just in case

<form action="https://site.com/tmp_name/submit.php" method="POST" id="modal-form" name="feedback_form" class="contact_form" enctype="multipart/form-data">
                        <ul>
                            <li>
                                <h2>Contact Us</h2>
                                <span class="required_notification">* Denotes Required Field</span>
                            </li>
                            <li>
                                <label>Name:</label>
                                <input type="text" name="user_name" placeholder="Username" required pattern="[A-z, А-я]{1,15}" id="name" />
                                <span class="form_hint">"Text"</span>  
                            </li>
                            <li>
                                <label>Email:</label>
                                <input type="email" name="user_email" placeholder="[email protected]" required id="email" />
                                <span class="form_hint">"[email protected]"</span>
                            </li>
                            <li>
                                <label>Website:</label>
                                <input type="url" name="user_website" placeholder="http://raidgir.com" required pattern="(http|https)://.+" id="website" />
                                <span class="form_hint">"http://example.com"</span>
                            </li>
                            <li>
                                <label>Phone:</label>
                                <input type="tel" name="user_phone" placeholder="+1 212 123 45 67" required pattern="^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$" id="phone" /> 
                                <span class="form_hint">"+1 212 123 45 67"</span>
                            </li>
                            <li>
                                <label>File:</label>
                                <input type="hidden" name="max_file_size" value="10000000" /> 
                                <input type="file" name="userfile[]" value="1" class="upload_files" multiple="yes" />  <!-- onchange="handleFiles(this.files)" -->
                            </li>
                            <li>
                                <label>Message:</label>
                                <textarea name="user_comment" cols="40" rows="6" required pattern="[A-z, А-я, 0-9]{1,15}" id="message"></textarea> 
                                <span class="form_hint mes">"Text"</span>   
                            </li>
                        </ul>
                        <button type="submit" id="btnSend" name="sendMail" class="submit">Submit Form</button>   
                    </form>


What could be the problem? Maybe someone will tell? Thank you for your attention!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Levchenko, 2020-12-05
@nuykon

1) Open the dev tools of the browser, for example in Google Chrome, open the network tab there, put a label on XHR just below. We look at whether the request is being sent, what is in the request body and what is in the response body
5fcb33db56568689625910.png
. If the request is successful and in the response you see -

<b>Your message sent!</b><br><br><pre><b> <a href="https://site.com" style="text-decoration:none;"> ⬅ Back to page</a></b></pre>
means $mail->send() worked. If at the same time the letter did not come, then most likely the mail function is disabled on the hosting.
Usually, during the test period, some hosters have it disabled and you need to contact support.
2) Checking whether the sending function is enabled on the hosting is quite simple, use the standard php function, create the php script mail-test.php and place it in the root of your site:
<?php
// Сообщение
$message = "Line 1\r\nLine 2\r\nLine 3";

// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap($message, 70, "\r\n");

// Отправляем
mail('[email protected]', 'My Subject', $message);
?>

Follow the link you.domain/mail-test.php
If you didn't receive a letter, then the function is disabled on the hosting and you need to write to the support service.
3) If the letter has arrived, then something is wrong in your sending script.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question