S
S
STig2252018-01-20 15:47:47
PHP
STig225, 2018-01-20 15:47:47

SMTP feedback form on PHPMailer with file attachments - why are attachments not coming to the mail?

Good afternoon everyone!
There is a feedback form with sending via SMTP using the PHPMailer library .
Opens in a modal window and works without reloading the page.
The HTML form looks like this:

<form action="letter.php" method="post" id="contact" enctype="multipart/form-data">

<label for="name">Имя:</label>
<input type="text" name="name" id="name" placeholder="Введите имя" required>

<label for="nomer">Телефон:</label>
<input type="text" name="nomer" id="nomer" placeholder="Ваш телефон" required>

<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder="Ваш e-mail" required>

<label for="body">Сообщение:</label>
<textarea name="body" id="body" placeholder="Наберите сообщение" required></textarea>

<label for='userfile[]'>Выберите файл:</label>
<input type="file" name="userfile[]" id="userfile" multiple>

<label for="check"><input type="checkbox" id="check">...</label>

<input type="hidden" name="validac" class="validac" value="validac_disabled">
<input id="submit" type="submit" name="submit" value="Отправить" disabled>

</form>

php handler - letter.php :
<?php

if( $_POST){

  require 'phpmailer.php';
  require 'smtp.php';
  
$mail = new PHPMailer;
$mail->isSMTP();

// Настройки
  $mail->Host = 'smtp.server.ru';
  $mail->SMTPAuth = true;
  $mail->CharSet = 'UTF-8';
  $mail->Username = '[email protected]'; // логин от вашей почты
  $mail->Password = 'Password'; // пароль от почтового ящика
  $mail->SMTPSecure = 'ssl';
  $mail->Port = '465';
  $mail->From = '[email protected]'; // адрес почты, с которой идет отправка
  $mail->FromName = 'Сообщение с domain.ru'; // имя отправителя
  $mail->addAddress('[email protected]');
 
 // Прикрепление файлов
  for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
        $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
        $filename = $_FILES['userfile']['name'][$ct];
        if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
            $mail->addAttachment($uploadfile, $filename);
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    }
 
// Письмо
$mail->isHTML(true);
$mail->Body = "Имя: {$_POST['name']}<br> Телефон: {$_POST['nomer']}<br> Email: {$_POST['email']}<br> Сообщение: " . nl2br($_POST['body']);
$mail->AltBody = "Имя: {$_POST['name']}\r\n Телефон: {$_POST['nomer']}\r\n Email: {$_POST['email']}\r\n Сообщение: {$_POST['body']}";
//	$mail->SMTPDebug = 0;

  if( $mail->send() ){
    $answer = '1';
  }else{
    $answer = '0';
    echo 'Письмо не может быть отправлено. ';
    echo 'Ошибка: ' . $mail->ErrorInfo;
  }
  die( $answer );
}

?>

Then I attach the jquery-3.2.1.min library , and I attribute the Ajax script to submit the form without reloading the page:
/*message*/
$(function(){
  $('#contact').submit(function(){
    var errors = false;
    $(this).find('span').empty();
    $(this).find('input, textarea').each(function(){
      if( $.trim( $(this).val() ) == '' ) {
        errors = true;
        $(this).next().text( 'Не заполнено поле ' + $(this).prev().text() );
      }
    });
    if( !errors ){
      var data = $('#contact').serialize();
      $.ajax({
        url: 'letter.php',
        type: 'POST',
        data: data,
        beforeSend: function(){
          $('#submit').next().text('Отправляю...');
        },
        success: function(res){
          if( res == 1 ){
            $('#contact').find('input:not(#submit), textarea').val('');
            $('#submit').next().empty();
            alert('Письмо отправлено');
          }else{
            $('#submit').next().empty();
            alert('Ошибка отправки');
          }
        },
        error: function(){
          alert('Ошибка!');
        }
      });
    }
    return false;
  });
});

The problem is that letters come without attachments.
I don’t know how to implement it correctly so that sending files to mail works. And it is desirable to attach several files to the letter with validation (restrictions on the size and extension of files)
What should the correct code look like?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2018-01-20
@dimonchik2013

decompose
make the local file
come in then make sure the locally loaded file is saved
then connect

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question