How to send data from a form with attached file to an email with PHP and AJAX?

Asked

Viewed 912 times

1

I’m trying to send a file using the function mail() of php, problem that I am doing the tests and the email is sent but will not the file and the email is sent totally uncompromised, which may be?

My codes are like this :

My form:

<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>

My AJAX function:

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

My php to send the 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);
}
  • 1

    The serialize function does not work to send a form with files through ajax. You have to use the javascript Formdata class.

  • @lvr7how would I do this, because I made the exchange here adding data: new FormData(this), in place of data: $("form").serialize(), and it wasn’t, it’s carrying and not the return

  • Which library is being used for sending emails?

  • PHP mail() same @Oliveira

1 answer

3


Change the passage $("form").serialize() and use the FormData to send file data. var data = new FormData($("form[name='contactform']")[0]);, also put the projects processData: false and contentType: false and remove the section dataType: 'JSON'

function contato(response) {
    var server = 'http://' + window.location.hostname + "/contato/ajaxResponse.php?acao=" + response;
    var loader = $('section.loader');
    loader.fadeIn(400);

    var data = new FormData($("form[name='contactform']")[0]);
    $.ajax({
        url: server,
        data: data,
        cache: false,
        type: "POST",
        processData: false,
        contentType: false
    }).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;
}
  • Until it worked, however the email is not being sent everything configured, send only the attachment without the body of the email and sender data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.