Отправка электронной почты с вложением PDF файлов с помощью PHP

Хорошо, ребята, это моя первая тема, и я искал в Интернете, но не повезло. Я прохожу практику, и я работаю над проектом, который требует, чтобы я создал веб-страницу, которая генерирует файл pdf, когда пользователь отправляет свою информацию. Как только клиент нажимает на кнопку отправки, должны произойти три вещи:

  1. Сохранить информацию в базе данных (сделано),
  2. Отправить сотрудникам электронное письмо с информацией о новом клиенте (сделано), и
  3. Отправить клиенту электронное письмо "благодарственное сообщение" с вложением файла pdf (не работает).

То есть, клиент получает письмо, но когда он/она открывает pdf-файл, я получаю следующее сообщение об ошибке:

"Acrobat не смог открыть 'имя_файла', потому что это либо не поддерживаемый тип файла, либо файл был поврежден (например, он был отправлен как вложение электронной почты и не был правильно декодирован)..."

Пожалуйста, имейте в виду, что я впервые делаю проект по созданию вложения файла pdf. Если кто-то может помочь мне решить эту проблему, это было бы здорово. Спасибо!

Вот мой код:

<?php
// once there are no errors, as soon as the customer hits the submit button, it needs to send an email to the staff with the customer information
        $msg = "Name: " .$_POST['name'] . "\n"
            ."Email: " .$_POST['email'] . "\n"
            ."Phone: " .$_POST['telephone'] . "\n"
            ."Number Of Guests: " .$_POST['numberOfGuests'] . "\n"
            ."Date Of Reunion: " .$_POST['date'];
        $staffEmail = "staffinfo";

        mail($staffEmail, "You have a new customer", $msg); // using the mail php function to send the email. mail(to, subject line, message)

        //once the customer submits his/her information, he/she will receive a thank you message attach with a pdf file.
        $pdf=new FPDF();
        $pdf->AddPage();
        $pdf->SetFont("Arial", "B", 16);
        $pdf->Cell(40, 10, "Hello World!");

        // email information
        $to = $_POST['email'];
        $from = $staffEmail;
        $subject = "Thank you for your business";
        $message = "Thank you for submitting your information!";

        // a random hash will be necessary to send mixed content
        $separator = md5(time());

        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // attachment name
        $filename = "yourinformation.pdf";

        // encode data (puts attachment in proper format)
        $pdfdoc = $pdf->Output("", "S");
        $attachment = chunk_split(base64_encode($pdfdoc));

        // encode data (multipart mandatory)
        $headers = "From: ".$from.$eol;
        $headers .= "MIME-Version: 1.0".$eol;
        $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol;
        $headers .= "Content-Transfer-Enconding: 7bit".$eol;
        $headers .= "This is a MIME encoded message.".$eol.$eol;

        // message
        $headers .= "--".$separator.$eol;
        $headers .= "Content-Type: text/html; charsrt=\"iso-8859-1\"".$eol;
        $headers .= $message.$eol.$eol;

        // attachment
        $headers .= "--".$separator.$eol;
        //$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
        $headers .= "Content-Type: application/zip; name=\"".$filename."\"".$eol;
        $headers .= "Content-Transfer-Encoding: base64".$eol;
        $headers .= "Content-Disposition: attachment".$eol.$eol;
        $headers .= $attachment.$eol.$eol;
        $headers .= "--".$separator."--";

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

    }
}
?>
7
задан ghoti 13 December 2011 в 17:11
поделиться