Jump to content

JQuery AJax attaching multiple files to email


Recommended Posts

Hello!I have simple form, sending email to me with data on finish, including one image attachment.



Let me show You part of my code that is responsible for getting and sending data:


Sample Structure

....    <div>      <label for="file_attach">Upload a screenshot from your HM2/PT4</label>      <input type="file" name="file_attach" id="file_attach" class="required" />    </div>  </div></section><h3>Another step</h3><section>  <div class="leftside">    <div>      <label for="maingoal">What is your main goal?</label>      <textarea name="maingoal" id="maingoal" class="required" cols="50" rows="5">      </textarea>    </div>...

Javascript handler (It's only the part that is executing after submitting corretly filled form)

onFinished: function (event, currentIndex){  var proceed = true;		  var m_data = new FormData();        m_data.append( 'firstName', $('input[name=firstName]').val());    m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);    m_data.append( 'maingoal', $('textarea[name=maingoal]').val());    //getting values from fields            			    $.ajax({      url: 'PHPHANDLER.php',      data: m_data,      processData: false,      contentType: false,      type: 'POST',      dataType:'json',      success: function(response){        //load json data from server and output message             if(response.type == 'error'){            output = '<div class="error">'+response.text+'</div>';        }else{          //success redirect      }			}      $("#example-form #contact_results").hide().html(output).slideDown();      }    });         }

And PHP file that is used by this javascript to send a message:

//check if its an ajax request, exit if notif(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {  $output = json_encode(array( //create JSON data    'type'=>'error',    'text' => 'Sorry Request must be Ajax POST'  ));  die($output); //exit script outputting json data}$firstName     = filter_var($_POST["firstName"], FILTER_SANITIZE_STRING);$maingoal      = filter_var($_POST["maingoal"], FILTER_SANITIZE_STRING);//additional simple php validationif(strlen($firstName)<2){ // If length is less than 4 it will output JSON error.  $output = json_encode(array('type'=>'error', 'text' => 'First name is too short or empty!'));  die($output);}else{//email body$message_body = "it doesn't matter";### Attachment Preparation ###$file_attached = false;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{  $boundary = md5("sanwebe");   //header  $headers = "MIME-Version: 1.0rn";   $headers .= "From:".$from_email."rn";   $headers .= "Reply-To: ".$email."" . "rn";  $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";           //plain text   $body = "--$boundaryrn";  $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";  $body .= "Content-Transfer-Encoding: base64rnrn";   $body .= chunk_split(base64_encode($message_body));           //attachment  $body .= "--$boundaryrn";  $body .="Content-Type: $file_type; name="$file_name"rn";  $body .="Content-Disposition: attachment; filename="$file_name"rn";  $body .="Content-Transfer-Encoding: base64rn";  $body .="X-Attachment-Id: ".rand(1000,99999)."rnrn";   $body .= $encoded_content; }else{  //proceed with PHP email.  $headers = "From:".$from_email."rn".  'Reply-To: '.$email.'' . "n" .  'X-Mailer: PHP/' . phpversion();  $body = $message_body;}$send_mail = mail($to_email, $subject, $body, $headers);   if(!$send_mail){  //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)  $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' => 'Hey '.$firstName .'! Your application has been sent and it's waiting for approve.'));  die($output);  }}

This all code is doing job for me with sending user data and one image.I was trying a couple of modifications but couldn't get this to work for more attachments. Any1 please help me rebuild it to my needs :)

Edited by LazyDragon
Link to comment
Share on other sites

The simplest way is to just copy and paste the parts of the code dealing with the file to add more of them. It would probably be better to switch to a library like PHPMailer if you want to support multiple attachments though, rather than building the entire email body yourself.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...