I am writing a script to send mail with an attachment.

$file = "act.pdf"; // файл $mailTo = "rumyancevaa@afanasy.ru"; // кому $from = "rumyancevaa@afanasy.ru"; // от кого $subject = "Общественная приемная"; // тема письма $message = "Контактный телефон обратившегося "; // текст письма $r = sendMailAttachment($mailTo, $from, $subject, $message, $file); // отправка письма c вложением echo ($r)?'<center><h2 class="action_title">Ваша заявка отправлена! Скоро мы ее рассмотрим и позвоним вам!<h2></center>':'Ошибка. Письмо не отправлено!'; //$r = sendMailAttachment($mailTo, $from, $subject, $message); // отправка письма без вложения //echo ($r)?'Письмо отправлено':'Ошибка. Письмо не отправлено!'; function sendMailAttachment($mailTo, $from, $subject, $message, $file = false){ $separator = "---"; // разделитель в письме // Заголовки для письма $headers = "MIME-Version: 1.0\r\n"; $headers .= "From: $from\nReply-To: $from\n"; // задаем от кого письмо $headers .= "Content-Type: multipart/mixed; boundary=\"$separator\""; // в заголовке указываем разделитель // если письмо с вложением if($file){ $bodyMail = "--$separator\n"; // начало тела письма, выводим разделитель $bodyMail .= "Content-Type:text/html; charset=\"utf-8\"\n"; // кодировка письма $bodyMail .= "Content-Transfer-Encoding: 7bit\n\n"; // задаем конвертацию письма $bodyMail .= $message."\n"; // добавляем текст письма $bodyMail .= "--$separator\n"; $fileRead = fopen($file, "r"); // открываем файл $contentFile = fread($fileRead, filesize($file)); // считываем его до конца fclose($fileRead); // закрываем файл $bodyMail .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode(basename($file))."?=\n"; $bodyMail .= "Content-Transfer-Encoding: base64\n"; // кодировка файла $bodyMail .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode(basename($file))."?=\n\n"; $bodyMail .= chunk_split(base64_encode($contentFile))."\n"; // кодируем и прикрепляем файл $bodyMail .= "--".$separator ."--\n"; // письмо без вложения }else{ $bodyMail = $message; } $result = mail($mailTo, $subject, $bodyMail, $headers); // отправка письма return $result; } 

How can I add a second attachment from input type = "file" on the form?

    3 answers 3

    Three simple steps to solve this problem:

    1. Look at the calendar and clarify what age is now in the yard.
    2. Gently select this code, and press Del
    3. Download phpmailer
    4. Forget all these handicraft tinkering like a bad dream.

    As a result, the code should look like this:

     require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->setFrom('from@example.com', 'First Last'); $mail->addAddress('whoto@example.com', 'John Doe'); $mail->Subject = 'PHPMailer file sender'; $mail->msgHTML("My message body"); // Attach uploaded files $mail->addAttachment($filename1); $mail->addAttachment($filename2); $r = $mail->send(); 

    it should be understood that sending mail is not just copying any specific combinations of characters into your script, by accident, in the past century, the author of some antediluvian article worked by chance. This is a much more complicated process that involves many nuances. And therefore, sending mail should not be sculpted manually from improvised means on the go, but entrusted to a proven and streamlined solution.

    • Thank you very much! So the truth is much easier and faster. Everything you need was implemented! - ArtemDoom

    In the function, throw an array of $ _FILES and then parse it:

     function sendMailAttachment($mailTo, $From, $subject_text, $message, $_FILES){ $to = $mailTo; $EOL = "\r\n"; // ограничитель строк, некоторые почтовые сервера требуют \n - подобрать опытным путём $boundary = "--".md5(uniqid(time())); // любая строка, которой не будет ниже в потоке данных. $subject= '=?utf-8?B?' . base64_encode($subject_text) . '?='; $headers = "MIME-Version: 1.0;$EOL"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"$EOL"; $headers .= "From: $From\nReply-To: $From\n"; $multipart = "--$boundary$EOL"; $multipart .= "Content-Type: text/html; charset=utf-8$EOL"; $multipart .= "Content-Transfer-Encoding: base64$EOL"; $multipart .= $EOL; // раздел между заголовками и телом html-части $multipart .= chunk_split(base64_encode($message)); #начало вставки файлов foreach($_FILES["file"]["name"] as $key => $value){ $filename = $_FILES["file"]["tmp_name"][$key]; $file = fopen($filename, "rb"); $data = fread($file, filesize( $filename ) ); fclose($file); $NameFile = $_FILES["file"]["name"][$key]; // в этой переменной надо сформировать имя файла (без всякого пути); $File = $data; $multipart .= "$EOL--$boundary$EOL"; $multipart .= "Content-Type: application/octet-stream; name=\"$NameFile\"$EOL"; $multipart .= "Content-Transfer-Encoding: base64$EOL"; $multipart .= "Content-Disposition: attachment; filename=\"$NameFile\"$EOL"; $multipart .= $EOL; // раздел между заголовками и телом прикрепленного файла $multipart .= chunk_split(base64_encode($File)); } #>>конец вставки файлов $multipart .= "$EOL--$boundary--$EOL"; if(!mail($to, $subject, $multipart, $headers)){ echo 'Письмо не отправлено'; } //Отправляем письмо else{ echo 'Письмо отправлено'; } } 

    PS: code tested for performance.

      $ _FILES is a global array, available everywhere, it is not necessary to pass to a function. PhpMailer mode is the best solution.