Skip to main content
<div class="contact_form">
    <div id="message"></div>
    <form id="contactform" action="" name="contactform" method="post" enctype="multipart/form-data">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <input type="text" name="nome" id="nome" class="form-control" placeholder="Nome"> 
            <input type="text" name="email" id="email" class="form-control" placeholder="Email">
            <input type="text" name="telefone" id="telefone" class="form-control" placeholder="Telefone"> 
            <input type="text" name="cpf" id="cpf" class="form-control" placeholder="CPF">
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <input type="text" name="cidade" id="cidade" class="form-control" placeholder="Cidade/Estado">
            <div class="input-group">
                <label class="input-group-btn">
                    <span class="btn btn-primary form-control">
                        Anexar Arquivo&hellip;
                        <input type="file" name="arquivo" id="arquivo" class="form-control" style="display: none;" accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
                    </span>
                </label>
                <input type="text" class="form-control" name="fileArq" readonly>
            </div>
            <textarea class="form-control" name="msg" id="msg" rows="6" placeholder="Mensagem"></textarea>
            <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right" onclick="return contato('email2');">ENVIAR</button>
        </div>
      </form>    
    </div>
   <script type="text/javascript">
 
     $(function() {

          // We can attach the `fileselect` event to all file inputs on the page
          $(document).on('change', ':file', function() {
         var input = $(this),
            numFiles = input.get(0).files ? input.get(0).files.length : 1,
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
          input.trigger('fileselect', [numFiles, label]);
          });

          // We can watch for our custom `fileselect` event like this
         $(document).ready( function() {
         $(':file').on('fileselect', function(event, numFiles, label) {

             var input = $(this).parents('.input-group').find(':text'),
                log = numFiles > 1 ? numFiles + ' files selected' : label;

              if( (input.length ) {
                input.val(log);
              } else {
                if( (log ) alert(log);
              }

           });
        });

     });
 
     </script>
function contato(response) {

    //(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change

    var server = 'https://'+window' + window.location.hostname;
    var loader = $('section.loader');
    loader.fadeIn(400);
    $.ajax({
            url: server+"server + "/contato/ajaxResponse.php?acao="+responseacao=" + response,
            data: $("form").serialize(),
            cache: false,
            type: "POST",
            dataType: 'JSON'
        })
        .done(function(ret) {

            if (ret.focus_error) {
                //retorno = true;
                focus_class(ret);

            }

            if (ret.status == 1) {
                alert("seus dados foram enviados com sucesso");
                clear_forms();
                window.location.reload();
            } else {
                console.log(ret); 
            }
        })
        .fail(function() { 
  
           alert("Um erro aconteceu, tente novamente"); 
        });

    loader.fadeOut(400);
    return false;

    // })(jQuery);

 
}
<div class="contact_form">
  <div id="message"></div>
  <form id="contactform" action="" name="contactform" method="post" enctype="multipart/form-data">
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
     <input type="text" name="nome" id="nome" class="form-control" placeholder="Nome"> 
     <input type="text" name="email" id="email" class="form-control" placeholder="Email">
     <input type="text" name="telefone" id="telefone" class="form-control" placeholder="Telefone"> 
     <input type="text" name="cpf" id="cpf" class="form-control" placeholder="CPF">
   </div>
   <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
     <input type="text" name="cidade" id="cidade" class="form-control" placeholder="Cidade/Estado">
     <div class="input-group">
      <label class="input-group-btn">
        <span class="btn btn-primary form-control">
          Anexar Arquivo&hellip;
          <input type="file" name="arquivo" id="arquivo" class="form-control" style="display: none;" accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
        </span>
      </label>
          <input type="text" class="form-control" name="fileArq" readonly>
    </div>
          <textarea class="form-control" name="msg" id="msg" rows="6" placeholder="Mensagem"></textarea>
          <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right" onclick="return contato('email2');">ENVIAR</button>
        </div>
      </form>    
    </div>
   <script type="text/javascript">
 
     $(function() {

          // We can attach the `fileselect` event to all file inputs on the page
          $(document).on('change', ':file', function() {
         var input = $(this),
         numFiles = input.get(0).files ? input.get(0).files.length : 1,
         label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
          input.trigger('fileselect', [numFiles, label]);
          });

          // We can watch for our custom `fileselect` event like this
         $(document).ready( function() {
         $(':file').on('fileselect', function(event, numFiles, label) {

             var input = $(this).parents('.input-group').find(':text'),
             log = numFiles > 1 ? numFiles + ' files selected' : label;

              if( input.length ) {
                input.val(log);
              } else {
                if( log ) alert(log);
              }

           });
        });

     });
 
     </script>
function contato(response) {

//(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change

    var server = 'https://'+window.location.hostname;
    var loader = $('section.loader');
    loader.fadeIn(400);
    $.ajax({
        url: server+"/contato/ajaxResponse.php?acao="+response,
        data: $("form").serialize(),
        cache: false,
        type: "POST",
        dataType: 'JSON'
    })
    .done(function(ret) {

        if(ret.focus_error){
            //retorno = true;
            focus_class(ret);

        }

        if(ret.status == 1){
            alert("seus dados foram enviados com sucesso");
            clear_forms();
            window.location.reload();
        }else{
            console.log(ret); 
        }
    })
    .fail(function() {  
         alert("Um erro aconteceu, tente novamente"); 
    });

    loader.fadeOut(400);
    return false;

    // })(jQuery);

 
}
<div class="contact_form">
    <div id="message"></div>
    <form id="contactform" action="" name="contactform" method="post" enctype="multipart/form-data">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <input type="text" name="nome" id="nome" class="form-control" placeholder="Nome"> 
            <input type="text" name="email" id="email" class="form-control" placeholder="Email">
            <input type="text" name="telefone" id="telefone" class="form-control" placeholder="Telefone"> 
            <input type="text" name="cpf" id="cpf" class="form-control" placeholder="CPF">
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <input type="text" name="cidade" id="cidade" class="form-control" placeholder="Cidade/Estado">
            <div class="input-group">
                <label class="input-group-btn">
                    <span class="btn btn-primary form-control">
                        Anexar Arquivo&hellip;
                        <input type="file" name="arquivo" id="arquivo" class="form-control" style="display: none;" accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
                    </span>
                </label>
                <input type="text" class="form-control" name="fileArq" readonly>
            </div>
            <textarea class="form-control" name="msg" id="msg" rows="6" placeholder="Mensagem"></textarea>
            <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right" onclick="return contato('email2');">ENVIAR</button>
        </div>
    </form>    
</div>
<script type="text/javascript">
$(function() {

    // We can attach the `fileselect` event to all file inputs on the page
    $(document).on('change', ':file', function() {
        var input = $(this),
            numFiles = input.get(0).files ? input.get(0).files.length : 1,
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
        input.trigger('fileselect', [numFiles, label]);
    });

    // We can watch for our custom `fileselect` event like this
    $(document).ready(function() {
        $(':file').on('fileselect', function(event, numFiles, label) {

            var input = $(this).parents('.input-group').find(':text'),
                log = numFiles > 1 ? numFiles + ' files selected' : label;

            if (input.length) {
                input.val(log);
            } else {
                if (log) alert(log);
            }

        });
    });

});
</script>
function contato(response) {

    //(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change

    var server = 'https://' + window.location.hostname;
    var loader = $('section.loader');
    loader.fadeIn(400);
    $.ajax({
            url: server + "/contato/ajaxResponse.php?acao=" + response,
            data: $("form").serialize(),
            cache: false,
            type: "POST",
            dataType: 'JSON'
        })
        .done(function(ret) {

            if (ret.focus_error) {
                //retorno = true;
                focus_class(ret);

            }

            if (ret.status == 1) {
                alert("seus dados foram enviados com sucesso");
                clear_forms();
                window.location.reload();
            } else {
                console.log(ret);
            }
        })
        .fail(function() { 
            alert("Um erro aconteceu, tente novamente");
        });

    loader.fadeOut(400);
    return false;

    // })(jQuery);
}
Fonte Link
Tiago Ferezin
  • 1,6mil
  • 2
  • 20
  • 47

Como enviar dados de um formulário com arquivo em anexo para um e-mail com PHP e AJAX?

Estou tentando enviar um arquivo usando a função mail() do php, problema que estou fazendo os testes e o email é enviado mas não vai o arquivo e o email é enviado totalmente desconfigurado, o que pode ser?

Meus códigos estão assim :

Meu formulário:

<div class="contact_form">
  <div id="message"></div>
  <form id="contactform" action="" name="contactform" method="post" enctype="multipart/form-data">
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
     <input type="text" name="nome" id="nome" class="form-control" placeholder="Nome"> 
     <input type="text" name="email" id="email" class="form-control" placeholder="Email">
     <input type="text" name="telefone" id="telefone" class="form-control" placeholder="Telefone"> 
     <input type="text" name="cpf" id="cpf" class="form-control" placeholder="CPF">
   </div>
   <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
     <input type="text" name="cidade" id="cidade" class="form-control" placeholder="Cidade/Estado">
     <div class="input-group">
      <label class="input-group-btn">
        <span class="btn btn-primary form-control">
          Anexar Arquivo&hellip;
          <input type="file" name="arquivo" id="arquivo" class="form-control" style="display: none;" accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
        </span>
      </label>
          <input type="text" class="form-control" name="fileArq" readonly>
    </div>
          <textarea class="form-control" name="msg" id="msg" rows="6" placeholder="Mensagem"></textarea>
          <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right" onclick="return contato('email2');">ENVIAR</button>
        </div>
      </form>    
    </div>
   <script type="text/javascript">

     $(function() {

          // We can attach the `fileselect` event to all file inputs on the page
          $(document).on('change', ':file', function() {
         var input = $(this),
         numFiles = input.get(0).files ? input.get(0).files.length : 1,
         label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
          input.trigger('fileselect', [numFiles, label]);
          });

          // We can watch for our custom `fileselect` event like this
         $(document).ready( function() {
         $(':file').on('fileselect', function(event, numFiles, label) {

             var input = $(this).parents('.input-group').find(':text'),
             log = numFiles > 1 ? numFiles + ' files selected' : label;

              if( input.length ) {
                input.val(log);
              } else {
                if( log ) alert(log);
              }

           });
        });

     });

     </script>

Minha função AJAX:

function contato(response) {

//(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change

    var server = 'https://'+window.location.hostname;
    var loader = $('section.loader');
    loader.fadeIn(400);
    $.ajax({
        url: server+"/contato/ajaxResponse.php?acao="+response,
        data: $("form").serialize(),
        cache: false,
        type: "POST",
        dataType: 'JSON'
    })
    .done(function(ret) {

        if(ret.focus_error){
            //retorno = true;
            focus_class(ret);

        }

        if(ret.status == 1){
            alert("seus dados foram enviados com sucesso");
            clear_forms();
            window.location.reload();
        }else{
            console.log(ret); 
        }
    })
    .fail(function() {  
        alert("Um erro aconteceu, tente novamente"); 
    });

    loader.fadeOut(400);
    return false;

    // })(jQuery);


}

Meu php pra enviar o email:

extract($_POST);
switch ($_GET['acao']) {

       case 'email2':

try {
        // pontos que vai verificar
    verfy_post(array(
        "nome",
        "email",
        "telefone",
        "cpf",
        "cidade",
            //"msg"
    ));

    $path = $_FILES["arquivo"]["tmp_name"];
    $fileType = $_FILES["arquivo"]["type"];
    $fileName = $_FILES["arquivo"]["name"];
    //var_dump($path);
    //die();
    $fp = fopen($path, "rb");
    $anexo = fread($fp, filesize($path));
    $anexo = base64_encode($anexo);
    fclose($fp);
    //$anexo = "jddd";
    $boundary = "XYZ-".date("dmYis")."-ZYX";
        // corpo da msg
    $mensagem  = "--$boundary" . PHP_EOL;
    $mensagem .= "Content-Type: text/html; charset='utf-8'" . PHP_EOL;
    $mensagem .= "<b>Nome:</b> $nome<br>";
    $mensagem .= "<b>Email:</b> $email<br>";
    $mensagem .= "<b>Telefone:</b> $telefone<br>";
    $mensagem .= "<b>CPF:</b> $cpf<br>";
    $mensagem .= "<b>Cidade:</b> $cidade<br>";
    //$mensagem .= "<b>Anexo:</b> $anexo<br>";
    $mensagem .= "<br>";
    $mensagem .= "<b>Mensagem:</b><br>";
    $mensagem .= nl2br($msg);
    $mensagem .= "--$boundary" . PHP_EOL;

    //anexando o arquivo
    $mensagem .= "Content-Type: ". $fileType ."; name=\"". $fileName . "\"" . PHP_EOL;
    $mensagem .= "Content-Transfer-Encoding: base64" . PHP_EOL;
    $mensagem .= "Content-Disposition: attachment; filename=\"". $fileName . "\"" . PHP_EOL;
    $mensagem .= "$anexo" . PHP_EOL;
    $mensagem .= "--$boundary" . PHP_EOL;
    //console_log($mensagem);

    // envia a msg (nao mexer)

    //$nome = $email;

    enviaEmailComAnexo(array(
        'nome'=> $nome,
        'de'=> $email,
        'para'=> EMAIL_PARA,
        'assunto'=> EMAIL_ASSUNTO. " | Trabalhe Conosco",
        'msg'=>$mensagem
    ), $boundary);

    send(array('status' => '1'));
}

function enviaEmailComAnexo($arr, $boundary){
     extract($arr);
    //$boundary = "XYZ-".date("dmYis")."-ZYX";
    $headers  = 'MIME-Version: 1.0' . PHP_EOL;
    $headers .= "Content-Type: multipart/mixed; ";
    $headers .= "boundary=" . $boundary . PHP_EOL;
    $headers .= "$boundary" . PHP_EOL;
    $headers .= "From: ".$nome." <".$de.">\n";
    // Função que envia o e-mail
    mail($para, $assunto, $msg, $headers);
}