Sending attachments in a PHP email

I'm writing a script for sending mail with an attachment.

$file = "act.pdf"; // файл
$mailTo = "[email protected]"; // кому
$from = "[email protected]"; // от кого
$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?

Author: aleksandr barakin, 2015-10-07

3 answers

Three simple steps to solve this problem:

  1. Look at the calendar and find out what century it is now in the yard.
  2. Carefully select this code, and press the Del key
  3. Download phpmailer
  4. Forget all this artisanal picking like a bad dream.

As a result, the code should look something like this:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('[email protected]', 'First Last');
$mail->addAddress('[email protected]', '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 certain combinations of characters into your script, they accidentally worked in the last century for the author of some antediluvian article. This is a much more complex process that involves many nuances. And therefore, sending mail should not be molded manually from improvised tools on the go, but should be entrusted to a proven and well-established solution.

 10
Author: Ипатьев, 2015-10-07 08:08:52

Throw the $_FILES array into the function 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 'Письмо отправлено';
        }

    }

P.S.: the code has been checked for operability.

 5
Author: Alex, 2015-10-08 16:11:38

$_FILES - global array, available everywhere, not required to pass to the function. The method with PHPMailer is the best solution.

 0
Author: Igor Nedodaev, 2017-10-13 07:52:28