使用PHP发送带有PDF附件的电子邮件-文件已损坏

使用PHP发送带有PDF附件的电子邮件-文件已损坏,php,email,pdf,attachment,Php,Email,Pdf,Attachment,我是php新手,使用以下代码发送带有PDF附件的电子邮件。 代码似乎几乎可以工作了。将发送电子邮件并附上文件 但是,当试图打开该文件时,表示该文件已损坏 有人能告诉我哪里出了问题吗?提前谢谢 <?php $filename = 'My File.pdf'; $path = '/public_html'; $file = $path . "/" . $filename; $mailto = 'themark@gmail.com';

我是php新手,使用以下代码发送带有PDF附件的电子邮件。 代码似乎几乎可以工作了。将发送电子邮件并附上文件

但是,当试图打开该文件时,表示该文件已损坏

有人能告诉我哪里出了问题吗?提前谢谢

<?php
    $filename = 'My File.pdf';
    $path = '/public_html';
    $file = $path . "/" . $filename;

    $mailto = 'themark@gmail.com';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

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

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: Jennifer <jenniferk@gmail.co.uk>" . $eol;
    $headers .= "Reply-To: Jennifer <jenniferk@gmail.co.uk>" .$eol;
    $headers .= "Return-Path: Jennifer <jenniferk@gmail.co.uk>" .$eol;     // these two to set reply address
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

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

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }
    ?>


尝试手动组装正确的多部分邮件时出错了…请使用邮件程序库,如PHPMailer或Swift-mailer@CBroe很抱歉,我对PHP完全陌生,不明白这意味着什么。正确组装多部分邮件的语法很复杂,很容易出错。因此,与其手动执行此操作,不如使用专门为此目的编写的现有库,这样您就不必自己执行所有操作,只需调用它提供的方法,即可将附件添加到邮件中。