@avshivtseva

Как прикрепить файл картинку при отправке сообщения?

Не получается прикрепить файл к письму. В чем может быть причина?
Сама форма:
<div id="send-drawing-popup" class="zoom-anim-dialog mfp-hide">
	<h3 class="title">Пришлите свой чертеж</h3>
	<div class="subtitle">для бесплатного проектирования и расчета сметы</div>
	<form class="popup-form file-form" id="file-form" enctype="multipart/form-data" method="post">
		<input name="form_subject" type="hidden" value="Свой чертеж">
		<label>
			<i class="icon-user-silhouette"></i>
			<input name="nameFF" type="text" placeholder="Введите Ваше имя" required></label>
		<label>
			<i class="icon-phone-receiver"></i>
			<input name="phoneFF" type="tel" placeholder="Введите Ваш телефон" required></label>
		<label>
			<i class="icon-mail-black-envelope-symbol"></i>
			<input name="emailFF" type="email" placeholder="Введите Ваш email" required>
		</label>
		<label class="custom-file-box">
		  <span class="f-box">
		  	<span class="f-btn"><i class="load-icon"></i></span>
		  	<span class="filename">Загрузить фото</span>
		  </span>
		  <input name="fileFF" type="file" id="fileFF" required>
		</label>
		<button class="btn-accent" type="submit">Отправить</button>
	</form>
</div>


JS:
$(".file-form").each(function() {
		$(this).validate({
			errorPlacement: function(error,element) {
    		return true;
  		},
			submitHandler: function(form) {
				var th = $(form);
				$.ajax({
					type: "POST",
					url: "<?php echo get_template_directory_uri() ?>/mail/sendfile.php", //Change
					data: th.serialize(),
					error: function() {
						setTimeout(function() {
							swal({
								title: "Ошибка!",
								text: "Не удалось отправить сообщение.",
								html: true,
								type: "error",
								// customClass: "zoom-anim animated-custom",
								confirmButtonText: "Вернуться на сайт",
								confirmButtonColor: "#00B147",
								// animation: "false",
							});
							// Done Functions
						}, 1000);
						$.magnificPopup.close({
		          items: {
		              src: '#callback',
		              // src: '#leave-request-popup',
		          },
		          type: 'inline'
		      	});
					}
				}).done(function() {
					// alert("Спасибо за заявку!");
					if( th.data("loadfile") ) {
						location.href = th.data("loadfile"); //переадресуем на файл
					} else {
						setTimeout(function() {
							swal({
								title: "Спасибо! Ваша заявка получена!",
								text: "Наш менеджер свяжется с Вами в течение 10 минут для уточнения деталей",
								html: true,
								type: "success",
								// customClass: "zoom-anim animated-custom",
								confirmButtonText: "Вернуться на сайт",
								confirmButtonColor: "#00B147",
								// animation: "false",
							});

							// Done Functions
							th.trigger("reset");
						}, 1000);
						$.magnificPopup.close({
			          items: {
			              src: '#callback',
			              // src: '#leave-request-popup',
			          },
			          type: 'inline'
			      });
					}
				});
				return false;
			}
		});
	});


PHP (почты не указываю тут) :

<?php

if (isset ($_POST['nameFF'])) {

  $to = "почта получателя"; 

  $from = 'не указываю почту отправителя';

  $subject = "Получен чертеж  со страницы ".$_SERVER['HTTP_REFERER'];

  $message = "Имя: ".$_POST['nameFF']."\nТелефон: ".$_POST['phoneFF']."\nEmail: ".$_POST['emailFF']."\nIP: ".$_SERVER['REMOTE_ADDR'];

  $boundary = md5(date('r', time()));

  $filesize = '';

  $headers = "MIME-Version: 1.0\r\n";

  $headers .= "From: " . $from . "\r\n";

  $headers .= "Reply-To: " . $to . "\r\n";

  $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

  $message="

Content-Type: multipart/mixed; boundary=\"$boundary\"



--$boundary

Content-Type: text/plain; charset=\"utf-8\"

Content-Transfer-Encoding: 7bit



$message";

       for($i=0;$i<count($_FILES['fileFF']['name']);$i++) {

           if(is_uploaded_file($_FILES['fileFF']['tmp_name'][$i])) {

               $attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF']['tmp_name'][$i])));

               $filename = $_FILES['fileFF']['name'][$i];

               $filetype = $_FILES['fileFF']['type'][$i];

               $filesize += $_FILES['fileFF']['size'][$i];

               $message.="

--$boundary

Content-Type: \"$filetype\"; name=\"$filename\"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename=\"$filename\"

$attachment";

     }

   } /////

  // Внимание! Заголовки не должны содержать табов, иначе вложения не определятся почтовыми сервисами.

     if(is_uploaded_file($_FILES['fileFF']['tmp_name'])) {

         $attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF']['tmp_name'])));

         $filename = $_FILES['fileFF']['name'];

         $filetype = $_FILES['fileFF']['type'];

         $filesize += $_FILES['fileFF']['size'];

         $message.="

--$boundary

Content-Type: \"$filetype\"; name=\"$filename\"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename=\"$filename\"

$attachment";

     }

     if(is_uploaded_file($_FILES['fileFF1']['tmp_name'])) {

         $attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF1']['tmp_name'])));

         $filename = $_FILES['fileFF1']['name'];

         $filetype = $_FILES['fileFF1']['type'];

         $filesize += $_FILES['fileFF1']['size'];

         $message.="

--$boundary

Content-Type: \"$filetype\"; name=\"$filename\"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename=\"$filename\"

$attachment";

     }

    if(is_uploaded_file($_FILES['fileFF2']['tmp_name'])) {

              $attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF2']['tmp_name'])));

              $filename = $_FILES['fileFF2']['name'];

              $filetype = $_FILES['fileFF2']['type'];

              $filesize += $_FILES['fileFF2']['size'];

              $message.="
--$boundary

Content-Type: \"$filetype\"; name=\"$filename\"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename=\"$filename\"

$attachment";

    }

   $message.="

--$boundary--";
 

    mail($to, $subject, $message, $headers);

    echo $_POST['nameFF'].', Ваше сообщение получено, спасибо!';

}

?>
  • Вопрос задан
  • 666 просмотров
Пригласить эксперта
Ответы на вопрос 1
HeadOnFire
@HeadOnFire
PHP, Laravel & WordPress Evangelist
Раз уж вы тег WordPress поставили, и сайт у вас на нем - то делайте все как положено. Почитайте про работу с ajax, загрузку файлов и отправку писем с вложениями:

https://wp-kama.ru/id_2018/ajax-v-wordpress.html
https://wp-kama.ru/id_9026/jquery-ajax-zagruzka-fa...
https://codex.wordpress.org/Function_Reference/wp_...
https://developer.wordpress.org/reference/function...

Грубо говоря, WP из коробки предоставляет вам возможность обрабатывать ajax-запросы с фронта, загружать файлы (одновременно проводя проверку загружаемых файлов), отправлять письма с вложениями.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы