PHP邮件成功发送附件,但邮件为空

时间:2016-04-20 16:47:16

标签: php email message attachment

这是PHP发送简单邮件脚本的一部分。它确实从FPDF创建了一个PDF附件(此处不包含代码)+它添加了一些用户上传的附件。

如果我从$message移除了$mail_sent = @mail( $to, $subject, $message, $body, $headers );,它会很好地发送附件,但如果将$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"; 

?>

1 个答案:

答案 0 :(得分:0)

通过在PDF附件之前添加$body .= $message.$eol;来解决。