Question

Php code used:

    $boundary = uniqid("np");

    $header = "MIME-Version: 1.0\r\n" ;
    $header .= "From: $from\r\n";
    $header .= "To: $to\r\n";
    if (!is_null($reply_to)) $header .= "Reply-To: $reply_to \r\n";
    $header .= "Content-Type: multipart/mixed;boundary=" . $boundary . "\r\n";

    //here is the content body
    $message = "This is a multi part message in MIME format.\n\n";

    $message .= "--" . $boundary . "\n";
    $message .= "Content-type: text/html;charset=utf-8\n\n";

    $message .= "Hello, <BR> This is a text email, the <bold>html version</bold>.";
    $message .= "<BR>Regards";
    $message .= "<BR>Your Name";
    $message .= "\n\n--" . $boundary . "\n";

    $file_name = "file_01.txt";
    $file_content = "Ciao - file 1";
    $chunked_content = chunk_split(base64_encode($file_content));  

    $message .= "Content-Type: application/octet-stream; name=\"$file_name\"\n";
    $message .= "Content-Disposition: attachment; filename=\"$file_name\"\n"; 
    $message .= "Content-Transfer-Encoding: base64\n\\n" . $chunked_content . "\n\n";  
    $message .= "--{$boundary}--";  

Results: HTML Mail IS OK, there is the attached file with right filename but it's empty

What's wrong ?

Edit: ! tried to replace every \n with \r\n but the results is an empty mail..

Was it helpful?

Solution

I use the following code for email attachments. Try this

function mailWithAttachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message)
{
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\n";
    $header .= "Reply-To: ".$replyto."\n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\n\n";
    $header .= "This is a multi-part message in MIME format.\n";
    $header .= "--".$uid."\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\n";
    $header .= $message."\n\n";
    $header .= "--".$uid."\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\n\n";
    $header .= $content."\n\n";
    $header .= "--".$uid."--";
    if(mail($mailto, $subject, "", $header))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top