【发布时间】:2016-04-20 16:47:16
【问题描述】:
这是一个简单的 PHP 邮件发送脚本的一部分。它确实从 FPDF 创建了一个 PDF 附件(此处不包含代码)+ 它添加了更多用户上传的附件。
如果我从$mail_sent = @mail( $to, $subject, $message, $body, $headers ); 中删除$message,它会很好地发送附件,但是如果将$message 放回$mail_sent,它似乎会与附件混淆并留下一大块邮件中的文字。我想这与 MIME 边界有关,但我就是不知道问题出在哪里。
任何帮助将不胜感激。
<?php
$to = "to@mail.com";
$from = $_POST["from@mail.com"];
$subject = "Subject";
$message = "This is the message";
$eol = PHP_EOL;
$filename = "$filename.pdf";
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
$fileatt_name = isset($_POST['fileatt_name']) ? $_POST['fileatt_name'] : '';
// Header
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$headers = "From: $from\r".$eol .
$headers = "Bcc: ".$bcc."\r".$eol .
"MIME-Version: 1.0\r".$eol .
"Content-Type: multipart/mixed;\r".$eol .
" boundary=\"{$mime_boundary}\"";
$body = "This is a multi-part message in MIME format.".$eol.$eol .
"--{$mime_boundary}".$eol .
"Content-Type: text/plain; charset=\"iso-8859-1\"".$eol .
"Content-Transfer-Encoding: 7bit".$eol.$eol .
"".$eol.$eol;
// PDF-Attachment
$body .= "--{$mime_boundary}".$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body.="--{$mime_boundary}--".$eol;
// More attachments
foreach($_FILES as $userfile)
{
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if (file_exists($tmp_name))
{
if(is_uploaded_file($tmp_name))
{
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$body .= "--{$mime_boundary}".$eol .
"Content-Type: {$type};".$eol .
" name=\"{$name}\"".$eol .
"Content-Disposition: attachment;".$eol .
" filename=\"{$fileatt_name}\"".$eol .
"Content-Transfer-Encoding: base64".$eol.$eol .
$data . "".$eol.$eol;
}
}
// Send
$mail_sent = @mail( $to, $subject, $message, $body, $headers );
echo $mail_sent ? "Success" : "Failed";
?>
【问题讨论】:
-
类似,但附件没有损坏,只有消息部分。
-
不要构建自己的 mime 消息。使用 phpmailer 或 swiftmailer,这会将所有 mime 垃圾减少到一个
->AddAttachment()-type 调用,然后您可以继续处理更重要的事情。 -
RTM php.net/manual/en/function.mail.php 不是 5 个参数。
标签: php email message attachment