PHP如何在不损坏pdf附件的情况下发送pdf附件



我在一个发送pdf文件的简单函数上遇到了一些问题-电子邮件发送了,但当我试图打开它时,附件已损坏,所以很明显我的函数做错了。

如有任何帮助,我们将不胜感激。

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: ".$from_name." <".$from_mail.">rn";
$header .= "Reply-To: ".$replyto."rn";
$header .= "MIME-Version: 1.0rn";
$header .= "This is a multi-part message in MIME format.rn";
$header .= "--".$uid."rn";
$header .= "Content-Type: application/octet-stream; name="attachment.pdf"rn";
$header .= "Content-Transfer-Encoding: 7bitrnrn";
$header .= $message."rnrn";
$header .= "--".$uid."rn";
$header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; 
$header .= "Content-Transfer-Encoding: base64rn";
$header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
$header .= $content."rnrn";
$header .= "--".$uid."--";



wp_mail($mailto, $subject, $message, $header);

}

您的电子邮件标题有点偏离。一个合适的多部分消息看起来像这样:

Content-Transfer-Encoding: binary
Content-Type: multipart/mixed; boundary="_----------=_1458761739257530"
MIME-Version: 1.0
Date: xxxxx
From: xxxxx
To: xxxxx
Reply-To: xxxx
Subject: xxxx
This is a multi-part message in MIME format.
--_----------=_1458761739257530
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain
This is the plain-text part of my message
That's all.
--_----------=_1458761739257530
Content-Disposition: attachment; filename="myfile.pdf"
Content-Transfer-Encoding: base64
Content-Type: application/octet-stream; name="myfile.pdf"
<base64 content here>
--_----------=_1458761739257530--

但实际上,你不应该自己生成这样的标题——有很多方法可以把它搞砸。相反,可以使用任意数量的现有PHP库,这些库将为您生成MIME头、进行编码和处理邮件。

例如,您的发行版很可能包括PEAR模块"Mail"one_answers"Mail_Mime",或者您可以使用pear install Mail Mail_Mime 轻松安装它们

然后做一些类似的事情:

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    require_once('Mail.php');
    require_once('Mail/mime.php');
    $file = $path.$filename;
    $headers = array (
      'From'     => $from_mail,
      'To'       => $mailto,
      'Reply-To' => $replyto,
      'Subject'  => $subject,
    );
    $mime = new Mail_mime(array('eol' => "n"));
    $mime->SetTXTBody($message);
    $mime->addAttachment($file, 'application/octet-stream');
    $mime_body    = $mime->get();
    $mime_headers = $mime->headers($headers);
    $mail =& Mail::factory('mail');
    $mail->send($mailto, $mime_headers, $mime_body);
     if (PEAR::isError($mail)) {
      echo("<p>ERROR:" . $mail->getMessage() . "</p>n");
    } else {
      echo("<p>Message successfully sent!</p>n");
    }
}

相关内容

最新更新