Please help I am creating this contact form where everything is working fine but I am not getting attachment in the email, What am I doing wrong?

Here is the code

Here is the script I am using

<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //get input field values
        var company_name = $('input[name=coname]').val();
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_phone      = $('input[name=phone]').val();
        var file_attach     = $('input[name=file_attach]')[0].files[0];
        var user_message    = $('textarea[name=message]').val();
        var address = $('textarea[name=address]').val();
        var bnature = $('input[name=bnature]').val();
        var Desgination = $('input[name=Desgination]').val();
        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        var regEx = new RegExp("/[0-9]/");
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
        else if ($("#phone").val().length != 10 && !$("#phone").val().match(regEx))
        {
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
            }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            $(".loading-img").show(); //show loading image
            $(".submit_btn").hide(); //hide submit button

            //data to be sent to server         
            var post_data = new FormData();    
            post_data.append( 'userName', user_name );
            post_data.append( 'userEmail', user_email );
            post_data.append( 'userPhone', user_phone );
            post_data.append('userMessage', user_message);
            post_data.append('companyname', company_name);
            post_data.append(('address'), address);
            post_data.append(('bnature'), address);
            post_data.append(('Desgination'), Desgination);
            post_data.append( 'file_name', file_attach );

            //instead of $.post() we are using $.ajax()
            //that's because $.ajax() has more options and can be used more flexibly.
            $.ajax({
              url: '/contact-form-test/contact_me.php',
              data: post_data,
              processData: false,
              contentType: false,
              type: 'POST',
              dataType:'json',
              success: function(data){
                    //load json data from server and output message     
                    if(data.type == 'error')
                    {
                        output = '<div class="error">'+data.text+'</div>';
                    }else{
                        output = '<div class="success">'+data.text+'</div>';

                        //reset values in all input fields
                        $('#contact_form input').val(''); 
                        $('#contact_form textarea').val(''); 
                    }

                    $("#result").hide().html(output).slideDown(); //show results from server
                    $(".loading-img").hide(); //hide loading image
                    $(".submit_btn").show(); //show submit button
              }
            });

        }
    });

    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });

});
</script>

Html Form is here

<fieldset id="contact_form">
<legend>Contact Us</legend>
    <div id="result"></div>
    <div class="row-fluid">
        coname
                    <div class="span5">
                         <label for="coname"><span>Company Name</span>
    <input type="text" name="coname" id="Text1" class="input-block-level" placeholder="Enter Company Name" />
    </label>

    <label for="name"><span>Contact Person</span>
    <input type="text" name="name" id="name" class="input-block-level" placeholder="Contact Person Name" />
    </label>
      <div class="span7">
    <label for="address"><span>Address</span>
    <textarea name="address" id="Textarea1" class="input-block-level" placeholder="Enter Company Address" rows="8"></textarea>
    </label>
    </div>
 <label  for="Business Nature"><span>Bussiness Nature</span>
    <input type="text" class="input-block-level" name="bnature" id="email1" placeholder="Enter Business Nature" />
    </label>
    <label style="position:relative;left:-105px" for="email"><span>Email Address</span>
    <input type="email" class="input-block-level" name="email" id="email" placeholder="Enter Your Email" />
    </label>
    <label  for="Designation"><span>Desgination</span>
    <input type="text" class="input-block-level" name="Desgination" id="Text2" placeholder="Enter Your Designation" />
    </label>
    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" class="input-block-level" placeholder="Phone Number" />
    </label>
    </div>
       <div class="span7">
    <label for="message"><span>Enquiry</span>
      <textarea name="message" id="message" class="input-block-level" placeholder="Enter Your Message" rows="8"></textarea>
    </label>
     <label for="Specification"><span>Specification</span>
            <input type="file" name="file_attach" class="input-field" />
        </label>
    </div>

                </div>
    <label><span>&nbsp;</span>
    <button class="submit_btn btn btn-primary btn-large pull-right" id="submit_btn">Submit</button>
    <img src="/images/ajax-loader.gif" class="loading-img" style="display:none">
    </label>
</fieldset>


and here is the contact_me.php file

<?php
if($_POST)
{
    $to_Email       = "ankitprajapati562@gmail.com"; //Replace with recipient email address
    $from_Email     = "info@betterwebsites4u.biz"; //From email address (eg: no-reply@YOUR-DOMAIN.com)
    $subject        = 'Ah!! My email from Somebody out there...'; //Subject line for emails

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error', 
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    } 

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
    $companyname     = filter_var($_POST["companyname"], FILTER_SANITIZE_STRING);
    $address= filter_var($_POST["address"], FILTER_SANITIZE_STRING);
    $bnature=filter_var($_POST["bnature"], FILTER_SANITIZE_STRING);
    $Desgination=filter_var($_POST["Desgination"], FILTER_SANITIZE_STRING);



    $mail_body       .="\r\n\r\n";
    $mail_body       .= "\r\n\r\nCompany Name: ".$companyname; //sender name
    $mail_body       .= "\r\n\r\nContact Person: ".$user_Name; //sender name
    $mail_body       .="\r\nEmail: ".$user_Email; //sender email
    $mail_body       .="\r\nPhone: ".$user_Phone; //sender phone
    $mail_body        .= "\r\n\r\nEnquiry Message: ".$user_Message;
    $mail_body        .= "\r\n\r\nAddress: ".$address;
    $mail_body        .= "\r\n\r\nBussiness Nature: ".$bnature;
    $mail_body        .= "\r\n\r\nDesgination: ".$Desgination;


    //additional php validation

    if(strlen($companyname)<4) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'company name is too short or empty!'));
        die($output);
    }
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Contact Person is too short or empty!'));
        die($output);
    }
    if(strlen($address)<10) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Address is too short or empty!'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if(!is_numeric($user_Phone)) //check entered data is numbers
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
        die($output);
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }

    ### Attachment Preparation ###
    //$file_attached = false; //initially file is not attached

    if(isset($_FILES['file_attach'])) //check uploaded file
    {
        //get file details we need
        $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
        $file_name        = $_FILES['file_attach']['name'];
        $file_size        = $_FILES['file_attach']['size'];
        $file_type        = $_FILES['file_attach']['type'];
        $file_error       = $_FILES['file_attach']['error'];

        //exit script and output error if we encounter any
        if($file_error>0)
        {
            $mymsg = array( 
            1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
            2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
            3=>"The uploaded file was only partially uploaded", 
            4=>"No file was uploaded", 
            6=>"Missing a temporary folder" ); 

            $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
            die($output); 
        }

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

        //now we know we have the file for attachment, set $file_attached to true
        $file_attached = true;
    }

    if($file_attached) //continue if we have the file
    {
        # Mail headers should work with most clients (including thunderbird)
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
        $headers .= "From:".$from_Email."\r\n";
        $headers .= "Subject:".$subject."\r\n";
        $headers .= "Reply-To: ".$user_Email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";

        $headers .= "--".md5('boundary1')."\r\n";
        $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";

        $headers .= "--".md5('boundary2')."\r\n";
        $headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
        $headers .= $mail_body."\r\n\r\n";

        $headers .= "--".md5('boundary2')."--\r\n";
        $headers .= "--".md5('boundary1')."\r\n";
        $headers .= "Content-Type:  ".$file_type."; ";
        $headers .= "name=\"".$file_name."\"\r\n";
        $headers .= "Content-Transfer-Encoding:base64\r\n";
        $headers .= "Content-Disposition:attachment; ";
        $headers .= "filename=\"".$file_name."\"\r\n";
        $headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
        $headers .= $encoded_content."\r\n";
        $headers .= "--".md5('boundary1')."--"; 
    }else{
        # Mail headers for plain text mail
        $headers = 'From: '.$from_Email.'' . "\r\n" .
        'Reply-To: '.$user_Email.'' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    }

    //send the mail
    $sentMail = @mail($to_Email, $subject, $mail_body, $headers);

    if(!$sentMail) //output success or failure messages
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
        die($output);
    }
}
?>

This is what I done to post the images files for upload and crop

function postdata(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function (theFile) {
                        var dom = '<div style="position:relative;"><img id="tobecrop" src="' + theFile.target.result + '" alt="your image" style="width:100%" /><div id="resizeDiv" class="ui-widget-content trans-bg"></div></div>';

                        jConfirm(dom, 'crop?', function (r) {
                            if (r) {
                                var fd = new FormData();
                                var file_data = $('input[type="file"]')[0].files; // for multiple files
                                fd.append("file", file_data[0]);
                                fd.append("ori_w", $.alerts.width);
                                fd.append("width", width);
                                fd.append("height", height);
                                fd.append("x", x);
                                fd.append("y", y);
                                fd.append("pnm", $("#stockid").val());
                                //fd.append("pnm", "SD3");

                                $.ajax({
                                    url: 'img_process.php',
                                    type: 'POST',
                                    dataType: 'json',
                                    contentType: false,
                                    processData: false,
                                    data: fd,
                                    success: function (data) {
                                        if (data.success) {
                                            var imgurl = '<img class="thumb" src="' + data.path + '" />';
                                            $("#thumb").append(imgurl);
                                        }
                                    }
                                });
                            }
                        });
                        $('#resizeDiv').draggable({
                            containment: "parent",
                            drag: function (event, ui) {
                                x = ui.position.left;
                                y = ui.position.top;
                            }
                        }).resizable({
                            aspectRatio: true,
                            containment: "parent",
                            resize: function (event, ui) {
                                width = ui.size.width;
                                height = ui.size.height;
                            }
                        });
                    }
                    reader.readAsDataURL(input.files[0]);
                }
            }

With the code, I able to get the data using the $_FILE in my php

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.