PHP - 带附件的电子邮件会折叠原始邮件

时间:2013-11-26 15:15:18

标签: php email email-attachments

在了解更好的解决方案的同时,我使用手动PHP脚本将文件附加到要通过电子邮件发送的邮件中。该文件正确附加,我甚至可以看到该消息,但由于某种原因,原始消息($msg)崩溃了!所有那些\n\r我已经消失了。任何想法??

这是我的代码:

// construct message
$msg = "Beginning of message \n -------------------- \n\n";
$msg .= "some logic is added to the message using a loop with \r\n in between each item on the list.\r\n";
$msg .= "--\n The end of the message.";

// handle file upload
$attachment = $_FILES['uploaded']['tmp_name'];
$att_type = $_FILES['uploaded']['type'];
$att_name = $_FILES['uploaded']['name'];

if (is_uploaded_file($attachment)) {
  // read the file to be attached ('rb' = read binary)
  $file = fopen($attachment, 'rb');
  $data = fread($file, filesize($attachment));
  fclose($file);

  // generate a boundary string
  $semi_rand = md5(time());
  $mime_boundary = "==Multipart_Boundary_x[$semi_rand]x";

  // add the headers for a file attachment
  $headers .= "MIME-Version: 1.0\r\n" .
  "Content-Type: multipart/mixed; boundary=\"{$mime_boundary}\"\r\n\r\n";

  // MESSAGE GETS WRITTEN HERE
  // add a multipart boundary above the plain message
  $message = "This is a multi-part message in MIME format.\r\n" .
  "--{$mime_boundary}\r\n" .
  "Content-Type: text/html; charset=\"iso-8859-1\"\r\n\r\n";
  $message .= $msg . "\r\n\r\n";

  // add file attachment to the message
  $message .= "\r\n--{$mime_boundary}\r\n" .
  "Content-Type: {$att_type};\r\n" .
  " name=\"{$att_name}\"\n" .
  "Content-Disposition: attachment;" .
  " filename=\"{$att_name}\"\r\n\r\n" .
  $data . "\r\n" .
  "--{$mime_boundary}--\n";
}
else {
  $message = $msg;
}
$success = mail($to, $subject, $message, $headers);

当文件未上传时,消息到达时会有换行符。但是当附加文件时它会崩溃。为什么?任何帮助赞赏!否则这个脚本可以工作。

1 个答案:

答案 0 :(得分:0)

看起来您使用Content-Type: text/html告诉电子邮件客户端它是HTML电子邮件。大多数电子邮件客户端将通过纯文本版本显示电子邮件的HTML内容。这意味着\r\n将无效。您需要在HTML版本中使用<br />来获取换行符。