Send uploaded file as email attachment

345 Views Asked by At

I have a form with file upload. After the form is submitted it should send the file in an email. I am using a simple PHP script, but it doesn't work.

How can I send an uploaded file by email?

//Send Mail
        $file_tmp_name = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

//read from the uploaded file & base64_encode content for the mail
        $handle = fopen($file_tmp_name, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $encoded_content = chunk_split(base64_encode($content));


        $boundary = md5("sanwebe");
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:".$mail."\r\n";
        $headers .= "Reply-To: ".$mail."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = ".$boundary."\r\n\r\n";

        //plain text
        $body = "--".$boundary."\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($message));

        //attachment
        $body .= "--".$boundary."\r\n";
        $body .="Content-Type: ".$file_type."; name=".$file_name."\r\n";
        $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
        $body .="Content-Transfer-Encoding: base64\r\n";
        $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
        $body .= $encoded_content;


        send_mail($to,$subject,$body,$headers);
1

There are 1 best solutions below

0
On

do you have enctype='multipart/form-data' parameter at your form? e.g: <form name="form_name" action="send.php" method="post" enctype='multipart/form-data'>