Domanda

While aware of better solutions, I am using manual PHP script to attach a file to the message to be sent by email. The file gets attached properly and I can even see the message, but for some reason the original message ($msg) gets collapsed! All those \n\r 's I have disappear. Any ideas??

Here's my code:

// 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);

When the file is not uploaded, the message arrives with line breaks in it. But when the files is attached it collapses. Why? Any help appreciated! Otherwise this script works.

È stato utile?

Soluzione

Looks like you're telling the email client that it's an HTML email by using Content-Type: text/html. Most email clients will display the HTML content of an email over the plain text version. That means \r\n won't work. You'll need to use <br /> in the HTML version to get the line breaks.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top