I use the following code to create and send the csv file to a specific mail box in php. I can successfully receive the csv file, however, I do not understand why one more txt file called ATT00001.txt is attached also. Can anyone help me to take a look?
Here is the part of code for sending the mail:
// email fields: to, from, subject, and so on
$to = "you@home.com";
$from = "me@home.com";
$subject ="Test mail";
$message = "please check the csv out!";
$headers = "From: $from";
$fileName = pathtocsv;
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
$file = fopen($fileName,"rb");
$data = fread($file,filesize($fileName));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"record.csv\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"test.csv\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
mail($to, $subject, $message, $headers);
And when I view it, it is just an empty txt file. I open the mail in Outlook.
Changing the last boundary line:
$message .= "--{$mime_boundary}\n";
to:
$message .= "--{$mime_boundary}--\n";
Note the extra --
at the end.
RFC 2046 ( § 5.1.1 - Common Syntax [page 19]) states that:
The boundary delimiter line following the last body part is a
distinguished delimiter that indicates that no further body parts
will follow. Such a delimiter line is identical to the previous
delimiter lines, with the addition of two more hyphens after the
boundary parameter value.--gc0pJq0M:08jU534c0p--
Since the last boundary was missing, it seems to be the default behaviour that Outlook creates an attachment containing some extra data or an empty attachment.
The second answer here by James-Luo may also be valid. He states that adding an attachment to a MIME message prior to the message body can result in similar outcome with the attachments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With