R
R
rRiorico2015-11-06 21:55:50
JavaScript
rRiorico, 2015-11-06 21:55:50

Sending a file from a form to an e-mail?

Hello! Help please, who is not difficult.
There is a form:

<form id="form">
  <input type="text" name="name" placeholder="Ваше имя" required /><br />
  <input type="text" name="tel" placeholder="Ваш телефон" required /><br />
  <input type="file" name="file">
  <button>Отправить</button>
</form>

A script is connected to it, which collects data from the form and sends it to the server (as far as I understand):
$(document).ready(function() {

  $("#form").submit(function() {
    $.ajax({
      type: "POST",
      url: "mail.php",
      data: $(this).serialize()
    }).done(function() {
      $(this).find("input").val("");
      alert("Спасибо за заявку! Скоро мы с вами свяжемся.");
      $("#form").trigger("reset");
    });
    return false;
  });
  
});

And the whole thing is sent to the mail by such a construction in PHP:
<?php

$recepient = "[email protected]";
$sitename = "Название сайта";

$name = trim($_POST["name"]);
$phone = trim($_POST["tel"]);
$message = "Имя: $name \nТелефон: $phone";

$pagetitle = "Новая заявка с сайта \"$sitename\"";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $recepient");


It is necessary to fasten the ability to send files (from the third field of the form) to e-mail. In programming, you can say I'm a complete zero. I found in Google only that the serialize method is not suitable for this, you need to do it through FormData. I would be very grateful for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2015-11-07
@Stalker_RED

If you are really a complete zero, then there is a possibility that you will not be able to send files, or you will be transported for a very long time, which Sergey Sergeev hinted at .
Sending files via mail() is a thankless task, you will have to form headers manually and deal with the details of mail operation in detail.
It's easier to use libraries like PHPMailer , PEAR/Mail2 , etc.

V
Vahe, 2015-11-07
@vahe_2000

HTML
requiredenctype="multipart/form-data"

<form method="post" action="attach.php" enctype="multipart/form-data">
  <input type="text" name="email"/><br>
  <input type="file" name="attachment"/><br>
  <input type="submit" name="send">
</form>

Notice just some of the things
$content = chunk_split(base64_encode(file_get_conte­nts($file)));
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"­;\r\n\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$file_name."­\"\r\n\r\n";
$headers .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

and now php attach.php
<?php
if (isset($_POST['send'])) {
  if (!empty($_FILES['attachment']['name'])) {

    // некоторые переменные
    $file_name = $_FILES['attachment']['name'];
    $temp_name = $_FILES['attachment']['tmp_name'];
    $file_type = $_FILES['attachment']['type'];

    // получить расширение файла
    $base = basename($file_name);
    $extension = substr($base, strlen($base)-4,strlen($base));

    // только это типы файлов будет разрешено
    $allowed_extensions = array(".doc","docx",".pdf",".zip",".png");

    // убедитесь, что этот тип файла допускается
    if (in_array($extension, $allowed_extensions)) {
      
      // основы
      $from = $_POST['email'];
      $to = "[email protected]";
      $subject = "Subject";
      $message = "message";
    } else {

      //вещи, которые нужно
      $file = $temp_name;
      $content = chunk_split(base64_encode(file_get_contents($file)));
      $uid = md5(uniqid(time()));

      //
      $headers = "From: ". $from."\r\n";
      $headers = "MIME-Version: 1.0" . "\r\n";

      // Заявив, у нас есть несколько видов электронной почте (т.е. обычный текст и вложения)
      $headers .= "Content-type: multipart/mixed;boundary=\"".$uid."\"\r\n\r\n";
      $headers .= "This is a multi-part message in MIME format.\r\n":

      // Обычная текстовая часть
      $headers .= "--".$uid."\r\n";
      $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
      $headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
      $headers .= $message."\r\n\r\n";

      // Влажение файла
      $headers .= "--".$uid."\r\n";
      $headers .= "Content-Type:". $file_type.":name=\"".$file_name."\"\r\n";
      $headers .= "Content-Transfer-Encoding: base64\r\n";
      $headers .= "Content-Description: attachment;filename=\"".$file_name."\r\n";
      $headers .= $content."\r\n\r\n";

      // Oтправить по почте (сообщение не здесь, а в заголовке в нескольких части

      if (mail($to, $subject, "",$headers)) {
        echo "Спасибо за заявку! Скоро мы с вами свяжемся";
      } else {
        echo "Неполучилось";
      }

    } else {
      echo "тип файла не имеет";
    }

  } else {
    echo "файл не прикреплен";
  }
}
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question