我在发送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.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
wp_mail($mailto, $subject, $message, $header);
}
答案 0 :(得分:1)
您的电子邮件标题已关闭了很多。正确的多部分消息看起来像这样:
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”和“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");
}
}