Sending php email - Swift_attachment does not work

Asked

Viewed 132 times

2

I’m trying to send an email, but I can’t attach a file. The file is copied to the tmp uploads folder, I have checked and it is there. If I comment on the line that attaches the file, the email is sent, but instead it is not sent.

HTML:

    <div id="inscreverOportunidade" class="hideform inscreverOportunidade" style="display:none;">
        <div id="boxForm">
            <div class="formProf">
                <form action="#" method="post" enctype="multipart/form-data">
                    <div style="width:100%;" class="big-new-close" onclick="javascript:showForm('');"><span>X</span></div>
                    <div class="to">
                        <div class="small-text"> NOME*</div>
                        <input type="text" required="true" class="input-text" value="" id="NomeO" name="NomeO" onfocus="this.value = '';" onblur="if (this.value == '') {
                                    this.value = '';
                                    }">
                    </div>
                    <div class="to email">
                        <div class="small-text">  EMAIL*</div>
                        <input type="email" required="true" class="text" value="" id="EmailO" name="EmailO" onfocus="this.value = '';" onblur="if (this.value == '') {
                                    this.value = '';
                                    }" >
                    </div>
                    <div class="to">
                        <div class="small-text"> CONTACTO*</div>
                        <input type="text" required="true" class="input-text" value="" id="ContactoO" name="ContactoO" onfocus="this.value = '';" onblur="if (this.value == '') {
                                    this.value = '';
                                    }">
                    </div>
                    <div class="to email">
                        <div class="small-text">  LOCALIDADE*</div>
                        <input type="text" required="true" class="text" value="" id="LocalidadeO" name="LocalidadeO" onfocus="this.value = '';" onblur="if (this.value == '') {
                                    this.value = '';
                                    }" >
                    </div>
                    <div class="to">
                        <div class="small-text"> PROFISSÃO*</div>
                        <input type="text" required="true" class="input-text" value="" id="ProfissaoO" name="ProfissaoO" onfocus="this.value = '';" onblur="if (this.value == '') {
                                    this.value = '';
                                    }">
                    </div>
                    <div class="to email">
                        <div class="small-text">  ANEXAR CURRÍCULO*</div>
                        <input type="file" required="true" name="CV" id="CV" class="text" accept=".docx, .doc, .pdf">
                    </div>
                    <div class="info">Os campos marcados com * são de preenchimento obrigatório</div>
                    <div class="submit-curriculo">
                        <input type="submit" id="enviar" value="Inscrever">
                    </div>
                </form>
            </div> <!--end formProf-->
        </div> <!--end boxForm-->
    </div>
    <script>
        $("#enviar").click(function(event){
            event.preventDefault();
            alert('1');
            var proceed = true;
            //simple validation at client's end
            //loop through each field and we simply change border color to red for invalid fields       
            $("#inscreverOportunidade input[required=true]").each(function () {
                $(this).css('border-color', '');
                if (!$.trim($(this).val()))
                { //if this field is empty 
                    $(this).css('border-color', 'red'); //change border color to red   
                    proceed = false; //set do not proceed flag
                }
                alert(proceed + '1');
                //check invalid email
                var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if ($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val())))
                {
                    $(this).css('border-color', 'red'); //change border color to red   
                    proceed = false; //set do not proceed flag              
                }
            });
            alert(proceed + '2');
            if (proceed) //everything looks good! proceed...
            {
                //data to be sent to server
                alert('inicio');
                var file_data = $('#CV').prop('files')[0];
                var form_data = new FormData();
                form_data.append('nome', $('input[name=NomeO]').val());
                form_data.append('email', $('input[name=EmailO]').val());
                form_data.append('contacto', $('input[name=ContactoO]').val());
                form_data.append('localidade', $('input[name=LocalidadeO]').val());
                form_data.append('profissao', $('input[name=ProfissaoO]').val());
                form_data.append('file', file_data);
                $.ajax({
                url: '<?php echo Yii::app()->createUrl('site/inscricaooportunidade'); ?>',
                        dataType: 'text',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function(result){
                        alert(result.text);
                        }
                });
                alert('fim');
            }
        });
    </script>

PHP:

    public function actionInscricaoOportunidade() {
        if (0 < $_FILES['file']['error']) {
            echo 'Error: ' . $_FILES['file']['error'] . '<br>';
        } else {
            move_uploaded_file($_FILES['file']['tmp_name'], 'tmp/' . $_FILES['file']['name']);
        }

        $target_dir = "tmp/";
        $target_dir = $target_dir . basename($_FILES["file"]["name"]);
        $uploadOk = 1;

        // Check if file already exists
        if (file_exists($target_dir . $_FILES["file"]["name"])) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }

        // Only PDF files allowed 
        if (!($uploadFile_type == "text/pdf")) {
            echo "Sorry, only PDF files are allowed.";
            $uploadOk = 0;
        }

        // Check if $uploadOk is set to 0 by an error
        if ($ok == 0) {
            echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
                echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }

        $mailbody = "Foi efectuada uma nova inscrição na oportunidade XXX com os seguintes dados:<br /><br />";
        $mailbody .= "<strong>NOME:</strong> " . $_POST['nome'] . "<br />";
        $mailbody .= "<strong>EMAIL:</strong> " . $_POST['email'] . "<br />";
        $mailbody .= "<strong>CONTACTO:</strong> " . $_POST['contacto'] . "<br />";
        $mailbody .= "<strong>Localidade:</strong> " . $_POST['localidade'] . "<br />";
        $mailbody .= "<strong>Profissão:</strong> " . $_POST['profissao'] . "<br /><br />";
        $mailbody .= "<strong>O Curriculo do candidato encontra-se anexado a este email</strong>";

        // Create the message
        $message = new YiiMailMessage;
        $message->setBody($mailbody, 'text/html');
        $message->subject = 'Confirmação de Inscricao - Oportunidade';

        $message->addTo("[email protected]");
        $message->from = $_POST['email'];

        $message->attach(\Swift_Attachment::fromPath($target_dir . basename($_FILES["file"]["name"])));

        return Yii::app()->mail->send($message);

    }

1 answer

1


Problem solved! It was almost all a matter of file path.

HTML:

    <div id="inscreverOportunidade" class="hideform inscreverOportunidade" style="display:none;">
        <div id="boxForm">
            <div class="formProf">
                <form action="#" method="post" enctype="multipart/form-data">
                    <div class="big-new-closeL">OPORTUNIDADE - CONTACTO</div>
                    <div class="big-new-closeR" onclick="javascript:showForm('');"><img alt="Fechar" src="images/cruz.jpg" /></div>
                    <div style="float:left;">
                        <div class="to">
                            <div class="small-text"> NOME*</div>
                            <input type="text" required="true" class="input-text" value="" id="NomeO" name="NomeO" onfocus="this.value = ''; return false;" onblur="if (this.value == '') {
                                        this.value = '';
                                        }">
                        </div>
                        <div class="to email">
                            <div class="small-text">  EMAIL*</div>
                            <input type="email" required="true" class="text" value="" id="EmailO" name="EmailO" onfocus="this.value = ''; return false;" onblur="if (this.value == '') {
                                        this.value = '';
                                        }" >
                        </div>
                        <div class="to">
                            <div class="small-text"> CONTACTO*</div>
                            <input type="text" required="true" class="input-text" value="" id="ContactoO" name="ContactoO" onfocus="this.value = ''; return false;" onblur="if (this.value == '') {
                                        this.value = '';
                                        }">
                        </div>
                        <div class="to email">
                            <div class="small-text">  LOCALIDADE*</div>
                            <input type="text" required="true" class="text" value="" id="LocalidadeO" name="LocalidadeO" onfocus="this.value = ''; return false;" onblur="if (this.value == '') {
                                        this.value = '';
                                        }" >
                        </div>
                        <div class="to">
                            <div class="small-text"> PROFISSÃO*</div>
                            <input type="text" required="true" class="input-text" value="" id="ProfissaoO" name="ProfissaoO" onfocus="this.value = ''; return false;" onblur="if (this.value == '') {
                                        this.value = '';
                                        }">
                        </div>
                        <div class="to email">
                            <div class="small-text">  ANEXAR CURRÍCULO*</div>
                            <input type="file" required="true" name="CV" id="CV" class="text" accept=".docx, .doc, .pdf">
                        </div>
                        <div class="info">Os campos marcados com * são de preenchimento obrigatório</div>
                        <div class="submit-curriculo">
                            <input type="submit" id="enviarBtn" value="Inscrever">
                        </div>
                    </div>
                </form>
            </div> <!--end formProf-->
        </div> <!--end boxForm-->
    </div>
    <script>
        $("#enviarBtn").click(function(event){
            event.preventDefault();
            var proceed = true;
            //simple validation at client's end
            //loop through each field and we simply change border color to red for invalid fields       
            $("#inscreverOportunidade input[required=true]").each(function () {
                $(this).css('border', '0');
                if (!$.trim($(this).val()))
                { //if this field is empty 
                    $(this).css('border', '1px solid red'); //change border color to red   
                    proceed = false; //set do not proceed flag
                }
                //check invalid email
                var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if ($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val())))
                {
                    $(this).css('border-color', 'red'); //change border color to red   
                    proceed = false; //set do not proceed flag              
                }
            });
            if (proceed) //everything looks good! proceed...
            {
                //data to be sent to server
                var file_data = $('#CV').prop('files')[0];
                var form_data = new FormData();
                form_data.append('nome', $('input[name=NomeO]').val());
                form_data.append('email', $('input[name=EmailO]').val());
                form_data.append('contacto', $('input[name=ContactoO]').val());
                form_data.append('localidade', $('input[name=LocalidadeO]').val());
                form_data.append('profissao', $('input[name=ProfissaoO]').val());
                form_data.append('file', file_data);
                $.ajax({
                url: '<?php echo Yii::app()->createUrl('site/inscricaooportunidade'); ?>',
                        dataType: 'text',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function(result){
                            if (result == "1")
                                alert("Ficheiro já existeste.");
                            if (result == "2")
                                alert("Erro ao enviar ficheiro.");
                            if (result == "3")
                                alert("Dados enviados com sucesso.");
                            if (result == "4")
                                alert("Erro ao enviar dados.");
                        }
                });
            }
        });
    </script>

PHP:

    public function actionInscricaoOportunidade() {

        $target_dir = "tmp/";
        $filename = basename($_FILES["file"]["name"]);

        // Check if file already exists
        if (file_exists($target_dir . $filename)) {
            echo "1"; //Sorry, file already exists
            exit();
        } else {
            if (!(move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir . $filename))) {
                echo "2"; //Sorry, there was an error uploading your file.";
            }
        }

        $mailbody = "Foi efectuada uma nova inscrição na oportunidade XXX com os seguintes dados:<br /><br />";
        $mailbody .= "<strong>NOME:</strong> " . $_POST['nome'] . "<br />";
        $mailbody .= "<strong>EMAIL:</strong> " . $_POST['email'] . "<br />";
        $mailbody .= "<strong>CONTACTO:</strong> " . $_POST['contacto'] . "<br />";
        $mailbody .= "<strong>Localidade:</strong> " . $_POST['localidade'] . "<br />";
        $mailbody .= "<strong>Profissão:</strong> " . $_POST['profissao'] . "<br /><br />";
        $mailbody .= "<strong>O Curriculo do candidato encontra-se anexado a este email</strong>";

        // Create the message
        $message = new YiiMailMessage;
        $message->setBody($mailbody, 'text/html');
        $message->subject = 'Confirmação de Inscricao - Oportunidade';

        //$message->addTo(Yii::app()->params['adminEmail']);
        $message->addTo("[email protected]");
        $message->from = $_POST['email'];

        $path = $target_dir . $filename;
        //$message->attach(\Swift_Attachment::fromPath($path));
        $message->attach(Swift_Attachment::fromPath($path));
        //$message->attach($path);
        if (Yii::app()->mail->send($message)) {
            echo "3"; //Sucesso
        } 
        else {
            echo "4"; //Erro
        }
        $transport = $this->container->get('mailer')->getTransport();  
        $spool = $transport->getSpool();
        $spool->flushQueue($this->container->get('swiftmailer.transport.real'));
        unlink($target_dir . $filename);
    }

Browser other questions tagged

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