尽管base64在标头中发送,但附件仍未被识别

时间:2014-04-28 11:48:57

标签: php email mime

我在php邮件中发送附件时遇到问题。问题是电子邮件似乎已发送并已收到,但未被识别为附件。如果我进入邮件来源,我可以看到它发送base64并包含附件名称,因此我很困惑,为什么它不会被客户识别。有什么想法吗?

$uid = md5(uniqid(time()));
$headers = "From: ".$from_name." <".$mailto.">\n";
$headers .= "Reply-To: ".$from_mail."\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "--".$uid."\n";
$headers .= "Content-type:text/plain\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= $message."\n";

foreach ($_FILES as $file) {
    $name = $file['name'];
    $handle = fopen($file['tmp_name'], "r");
    $content = fread($handle, $file['size']);
    fclose($handle);
    $content = chunk_split(base64_encode($content));

    $headers .= "--{$uid}\n";
    $headers .= "Content-Type: {$file['type']}; name=\"{$name}\"\n";
    $headers .= "Content-Transfer-Encoding: base64\n";
    $headers .= "Content-Disposition: attachment; filename=\"{$name}\"\n";
    $headers .= $content;
}

$headers .= "--{$uid}--";
$mailto = 'myemail@email.com';
return mail($mailto, $subject, $message, $headers, '-f' . $mailto);

1 个答案:

答案 0 :(得分:2)

问题

您的代码存在许多问题:

  • 电子邮件标头必须由CRLF终止。您只有LF
  • B64编码的文件和消息将添加到标头中。它们应该作为消息正文发送。
  • 邮件标题和每个部分中的邮件正文之间必须有一个额外的CRLF
  • 正文部分必须以以CRLF开头的分隔符分隔。

电子邮件语法

根据RFC 2046,这是多部分邮件正文结构的摘录。请特别注意CRLF。 (BNF语法,有点简化。)


multipart-body := [preamble CRLF]
                  dash-boundary CRLF
                  body-part *encapsulation
                  close-delimiter
                  [CRLF epilogue]

dash-boundary := "--" boundary

body-part := MIME-part-headers [CRLF *OCTET]

encapsulation := delimiter
                 CRLF body-part

delimiter := CRLF dash-boundary

close-delimiter := delimiter "--"

代码

您的代码可能如下所示:

$uid = md5(uniqid(time()));
$headers = "From: ".$from_name." <".$mailto.">\r\n";
$headers .= "Reply-To: ".$from_mail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n";

$body = "This is a multi-part message in MIME format.\n";
$body .= "--".$uid."\r\n";
$body .= "Content-type:text/plain\r\n";
$body .= "Content-Transfer-Encoding: 8bit\r\n";
$body .= "\r\n";
$body .= $message;

foreach ($_FILES as $file) {
  $name = $file['name'];
  $handle = fopen($file['tmp_name'], "r");
  $content = fread($handle, $file['size']);
  fclose($handle);
  $content = chunk_split(base64_encode($content));

  $body .= "\r\n--{$uid}\r\n";
  $body .= "Content-Type: {$file['type']}; name=\"{$name}\"\r\n";
  $body .= "Content-Transfer-Encoding: base64\r\n";
  $body .= "Content-Disposition: attachment; filename=\"{$name}\"\r\n";
  $body .= "\r\n";
  $body .= $content;
}

$body .= "\r\n--{$uid}--";
$mailto = 'myemail@email.example';
return mail($mailto, $subject, $body, $headers, '-f' . $mailto);

参考