I wanted to send an email that only contained an attachment as follows:
$headers = "MIME-Version: 1.0\r\n"; $headers .= "To: <".$to_email.">\r\n"; $headers .= "From: ".$from_name." <".$from_email.">"; $random_hash = md5(date('r', time())); // add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; // read the atachment file contents from a string previously formed, // encode it with MIME base64, // and split it into smaller chunks $attachment = chunk_split(base64_encode($content)); // construct the body of the message $message = "--PHP-mixed-".$random_hash; // my attachment was an html file $message .= "\r\nContent-Type: text/html; name=\"".$filename."\""; $message .= "\r\nContent-Transfer-Encoding: base64"; $message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n"; $message .= "\r\n--PHP-mixed-".$random_hash."--"; // Windows ini_set('sendmail_from', $return_email); mail($to_email, addslashes($subject), $message, $headers); ini_restore('sendmail_from'); // Linux // mail($to_email, addslashes($subject), $message, $headers, "-r ".$return_email);
I received an email with an attachment, but the problem was that the attached file had 0 bytes.
To my surprise, after comparing the source of the email with the source of an email with a complete attachment, I found out the problem: before the actual content of the attachment ($attachment) there should be an empty line.
I replaced the line of code:
$message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n";
$message .= "\r\nContent-Disposition: attachment\r\n\r\n".$attachment."\r\n"; // notice the double \r\n
and it worked! This way I received the email with the correct attachment.
7 replies on “The attachment of an email sent via PHP has 0 bytes”
hi? thank you for your script. but when i tried it, it didnt work for me. Please can i see how u attached your file? I just did $filename = “elist.txt”; please can i see the full script?
If you want to attach the contents of an existing file, you should first get the content of that file into the $content variable:
$file_path = "elist.txt"; //if the file you want to attach is not in the same directory as the script, you should set the appropriate path
$content = file_get_contents($file_path);
The $filename variable should contain the name of the attached file, that is the name under which you want the file to appear in the e-mail.
Hey, thanks for your tip to add an extra blank line before the actual content of the attachment, it saved me a lot of time!
Thanks for sharing this… also saved me a lot of troubleshooting!
Thank you….this helps a lot to me….
Thank you so much!!!!
You saved me!!
11 years after and you saved another one.
Thank you very much!