S
S
Sergey2015-11-01 13:44:28
PHP
Sergey, 2015-11-01 13:44:28

How to attach an excel document to an email via phpmail?

Good day! Help me solve the problem: I need to send an email with an attached xlsx document using php. The letter is sent, arrives successfully, but the file does not open - it says that it is damaged or has an unknown format.
The xlsx document is generated before sending the letter and saved on the server, manually opens normally. those. something happens to him at the moment of sending. Help me understand why! I hope for your help!

$file = "/pay/downloads/".$FULLNAME_STUDENT." - ".$today.".xlsx";
  $testexcel = $_SERVER["DOCUMENT_ROOT"] . $file;

    $to      = 'мойемэйл@mail.ru';
    $subject = 'тема письма';
    $html = 'Это письмо сгенерировано автоматически, отвечать на него не нужно.';

    $message = $html;

send_mail($to, $subject, $message,  $testexcel, $realname);

function send_mail($to, $subject, $message, $path, $realname)
  {
    $fp = fopen($path,"r");
    if (!$fp)
    {
      print "Файл $path не может быть прочитан";
      exit();
    }
    $file = fread($fp, filesize($path));
    fclose($fp);

    $boundary = "--".md5(uniqid(time())); // генерируем разделитель
    $headers2 = "MIME-Version: 1.0\n"; 
  $headers2 .='From: [email protected]' . "\r\n" .
    $headers2 .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
    $multipart .= "--$boundary\n"; 
    $kod = 'utf-8'; 
    $multipart .= "Content-Type: text/html; charset=$kod\n"; 
    $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
    $multipart .= "$message\n\n";
    //Блок файла 1
    $message_part .= "--$boundary\n";
    $message_part .= "Content-Type: application/xls; name=\"".$realname."\"\n\n";
    // $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: attachment; filename = \"".$realname."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";

 
    //Итоги
    $multipart .= $message_part."--$boundary--\n";
 
    if(!mail($to, $subject, $multipart, $headers2)){
      echo "К сожалению, письмо не отправлено";
      exit();
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2015-11-01
@RnD

$message_part .= "Content-Type: application/xls; name=\"".$realname."\"\n\n";

Here the second line feed is not superfluous?

A
Alexander Kubintsev, 2015-11-01
@akubintsev

It's good that you figured it out now, but I recommend making your life easier in the future with SwiftMailer swiftmailer.org/docs/messages.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question