【问题标题】:PHP - Email with attachment collapses original messagePHP - 带有附件的电子邮件折叠原始消息
【发布时间】:2013-11-26 15:15:18
【问题描述】:

虽然知道更好的解决方案,但我正在使用手动 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);

当文件未上传时,消息到达时带有换行符。但是,当附加文件时,它会崩溃。为什么?任何帮助表示赞赏!否则此脚本有效。

【问题讨论】:

    标签: php email email-attachments


    【解决方案1】:

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

    【讨论】:

    • 天哪!而已。我只是将其更改为 text/plain 并且它有效。现在一切都说得通了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2020-11-20
    • 2014-02-28
    • 2017-09-06
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多