Отправка файла и текста из формы на почту

В JS есть переменная message в которой хранятся проверенные текстовые данные из почтовой формы. и есть переменная file_data в которой как я понимаю храниться файл приложенный к письму. и есть обработчик PHP.

<?php $headers  = 'MIME-Version: 1.0' . '\r\n';
$headers  = 'Content-type: text/html; charset=windows-1251 \r\n';
$headers = 'From: Ваш сайт \r\n';
$admin_mail = 'Ваш почтовый адрес';
$subject = 'Письмо с Ваш сайт';
$message = $_POST['message'];
mail($admin_mail, $subject, $message, $headers);?>

Вопрос, как добавить этот файл или переменную file_data в ajax и php чтоб он тоже отправлялся на почту.

          var form_data = new FormData();
          file_data = $(nameform).find('input[type=file]').prop('files')[0];   
          form_data.append("file", file_data);

      $.ajax({
          url: '/send.php',
          type: 'post', 
          data: {message: message},
          success: function() {  
          }
      }); 

Ответы (1 шт):

Автор решения: Bohdan

JS:

          var form_data = new FormData();
          file_data = $(nameform).find('input[type=file]').prop('files')[0];   
          form_data.append("file", file_data);
          form_data.append("message", message);

      $.ajax({
          url: '/send.php',
          type: 'post', 
          data: form_data,
          success: function() {  
          }
      });

PHP:

<?php

    $admin_mail = 'Ваш почтовый адрес';
    $subject = 'Письмо с Ваш сайт';

    $message        = $_POST["message"] //body of the email

    //Get uploaded file data using $_FILES array
    $tmp_name    = $_FILES['file']['tmp_name']; // get the temporary file name of the file on the server
    $name        = $_FILES['file']['name'];  // get the name of the file
    $size        = $_FILES['file']['size'];  // get size of the file for size validation
    $type        = $_FILES['file']['type'];  // get type of the file
    $error       = $_FILES['file']['error']; // get the error (if any)
  
    //validate form field for attaching the file
    if($file_error > 0)
    {
        die('Upload error or No files uploaded');
    }
  
    //read from the uploaded file & base64_encode content
    $handle = fopen($tmp_name, "r");  // set the file handle only for reading the file
    $content = fread($handle, $size); // reading the file
    fclose($handle);                  // close upon completion
  
    $encoded_content = chunk_split(base64_encode($content));
  
    $boundary = md5("random"); // define boundary with a md5 hashed value
  
    //header
    $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
    $headers .= "From:".$admin_mail."\r\n"; // Sender Email
    $headers .= "Reply-To: ".$admin_mail."\r\n"; // Email addrress to reach back
    $headers .= "Content-Type: multipart/mixed;\r\n"; // Defining Content-Type
    $headers .= "boundary = $boundary\r\n"; //Defining the Boundary
          
    //plain text 
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
    $body .= chunk_split(base64_encode($message)); 
          
    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $file_type; name=".$file_name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n"; 
    $body .= $encoded_content; // Attaching the encoded file with email
      
    mail($admin_mail, $subject, $body, $headers);

php взят отсюда https://www.geeksforgeeks.org/php-send-attachment-email/

Но я бы советовал использовать api для отправки почты или хотя бы какую то библиотеку, например https://github.com/PHPMailer/PHPMailer

→ Ссылка