Send e-mail with attachment sent by input

Asked

Viewed 1,252 times

1

I have a PHP website with a contact form that allows me to upload a file. This file must then be sent in an e-mail together with the other data. The email is not being received, although you will receive the send confirmation message. It is also not in spam folders. I tried the company email, Gmail and Hotmail.

There is a PHP file with HTML that then makes a post (jQuery and AJAX) to a script PHP file. In this script file is the sending of email. I know that the sending function is being executed because I receive message from it.

html code:

    <div id="inscreverOportunidade" class="hideform inscreverOportunidade" style="display:none;">
        <div id="boxForm">
            <div class="formProf">
                    <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" name="submit" id="submit" value="Inscrever" onclick="javascript:sendFormRegO();
                            return false;"></div>
            </div> <!--end formProf-->
        </div> <!--end boxForm-->
    </div>
    <script>
        function sendFormRegO()
        {
            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
                }
                //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 m_data = new FormData();    
                m_data.append( 'nome', $('input[name=NomeO]').val());
                m_data.append( 'email', $('input[name=EmailO]').val());
                m_data.append( 'contacto', $('input[name=ContactoO]').val());
                m_data.append( 'localidade', $('input[name=LocalidadeO]').val());
                m_data.append( 'profissao', $('input[name=ProfissaoO]').val());
                m_data.append( 'file', $('input[name=CV]')[0].files[0]);

                //instead of $.post() we are using $.ajax()
                //that's because $.ajax() has more options and flexibly.
                $.ajax({
                  url: '<?php echo Yii::app()->createUrl('site/inscricaooportunidade'); ?>',
                  data: m_data,
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  dataType:'json',
                  success: function(response){
                      alert(response.text);
                     //load json data from server and output message     
                    if(response.type == 'error'){ //load json data from server and output message     
                        output = '<div class="error">'+response.text+'</div>';
                    }else{
                        output = '<div class="success">'+response.text+'</div>';
                    }
                  }
                });         
            }
        }
        </script>

PHP code:

    public function actionInscricaoOportunidade()
    {

        //if(Yii::app()->request->isAjaxRequest)
        if($_POST)
        {

            //check if its an ajax request, exit if not
            if(!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
            }

            //Sanitize input data using PHP filter_var().
            $nome      = filter_var($_POST['nome'], FILTER_SANITIZE_STRING);
            $email     = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
            $contacto   = filter_var($_POST['contacto'], FILTER_SANITIZE_STRING);
            $localidade   = filter_var($_POST['localidade'], FILTER_SANITIZE_STRING);
            $profissao        = filter_var($_POST['profissao'], FILTER_SANITIZE_STRING);

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

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

            ### Attachment Preparation ###
            $file_attached = false;
            if(isset($_FILES['file'])) //check uploaded file
            {
                //get file details we need
                $file_tmp_name    = $_FILES['file']['tmp_name'];
                $file_name        = $_FILES['file']['name'];
                $file_size        = $_FILES['file']['size'];
                $file_type        = $_FILES['file']['type'];
                $file_error       = $_FILES['file']['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
                $headers = "MIME-Version: 1.0\r\n";
                $headers = "X-Mailer: PHP/" . phpversion()."\r\n";
                $headers .= "From: ".$from_email."\r\n";
                $headers .= "Subject: Confirmação de Inscricao - Oportunidade\r\n";
                $headers .= "Reply-To: " .$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=utf-8\r\n\r\n";
                $headers .= $message_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{
                //proceed with PHP email.
                $headers = 'From: '.$nome.'' . "\r\n" .
                'Reply-To: '.$email.'' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
            }
            $send_mail = mail($to_email, "Confirmação de Inscricao - Oportunidade", $message_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' => 'Hi '.$nome .' Thank you for your email'));
                die($output);
            }
        }


    }
  • Voce could use this extension http://www.yiiframework.com/extension/yiimailer/ which already has what you want in a practical way

  • I also tried to use yiimailer, which was implemented by those who developed the project earlier, but it wasn’t working and I couldn’t fix it. I have never worked with the Yii platform before, and my knowledge of PHP is really very little

  • if the knowledge is little it advises you to study a lot to enter a framework without the knowledge due it is quite complicated

  • That’s what I’ve been doing, but this issue is something urgent

2 answers

1


Well... here’s a code I made in France... 14 years attracts (time...). It works. I don’t have time to translate, but it’s very easy to understand:

<?php

/*=============================================*/
/* ENVOI D'UN MAIL AVEC FICHIER JOINT EVENTUEL */
/*          PL Lamballais - PARX 2000          */
/*=============================================*/

/* Fichier: php.inc/send_mail.php3      */
/* Version 1.00 du 18/02/2000           */
/* Version 1.01 du 04/03/2000 Ajout de charset et du */
/* type MIME de l'envoi sans fichier joint pour avoir les accents. */

/* $dbug            => 0 = normal, 1 débug, donc on affiche les     infos. */
/* $mail_dest       => adresse email destination */
/* $mail_exp        => adresse email  expéditeur */
/* $mail_subject    => sujet du message */
/* $mail_msg        => corps du message */
/* $file_path       => chemin complet du fichier à joindre (rien si pas de fichier) */
/* $file_name       => nom du fichier devant apparaitre comme nom de pièce jointe */
/* $file_type       => type MIME du fichier à joindre */

function send_mail($dbug, $mail_dest,$mail_exp,$mail_subject,$mail_msg,$file_path,$file_name,$file_type)
{

if ($dbug == 1)
    {
        echo "Routine send_mail(). Mode débuggage<br />\n";
        echo "mail_dest = ".$mail_dest."<br />\n";
        echo "mail_exp = ".$mail_exp."<br />\n";
        echo "mail_subject = ".$mail_subject."<br />\n";
        echo "mail_msg = ".$mail_msg."<br />\n";
        echo "file_path = ".$file_path."<br />\n";
        echo "file_name = ".$file_name."<br />\n";
        echo "file_type = ".$file_type."<br     />\n";                                          
    }



/* Définition des éléments d'en-tête du mail */
/* Ce sont les éléments par défaut donc sans fichier joint */
    $boundary="-----------------kjbsdf9873987348735";
    $MIME = "MIME-Version: 1.0\nContent-Type:text/plain;\n\tcharset=\"utf-8\"\nContent-Transfer-Encoding: 8bit\n\n";
    $startMsg = "";
    $ending = "";


/*= Préparation du début du message =*/

    $hold_message = $mail_msg."\n\n";

/*= S'il y a un fichier, on l'encode =*/
    if ($file_path != "")
    {

    /* Vérifions l'existence de ce fichier */
    $tst = file_exists($file_path);
    if ($tst == false)
        {
            if ($dbug == 1)
                {
                    echo "== Erreur: le fichier ".$file_path." est introuvable.<br />\n";                   
            }   
        }
    else
        {
        $fp=fopen($file_path,"r");                      /* Ouvre le fichier */
        $in = fread( $fp, filesize( $file_path));       /* Lecture des données */
        fclose( $fp );                                  /* Fermeture fichier */
        $data_encode= chunk_split(base64_encode($in));  /* Encodage */

        if ($dbug == 1)
            {
                $taille = strlen($data_encode);
                echo "Taille des données Base64 : ".$taille."<br />\n";

            }

    /* Puisqu'il y a un fichier joint, on change le début et la fin du message */
        $startMsg = "\n--$boundary\nContent-Type:text/plain;\n\tcharset=\"utf-8\"\nContent-Transfer-Encoding: 8bit\n\n";
        $ending = "\n--$boundary--";

        $MIME = "MIME-Version: 1.0\nContent-Type:multipart/mixed;\n\tboundary=\"$boundary\"\n\nThis is a multi-part message in MIME format.\n\n";
        $hold_message = $hold_message."\n--$boundary\nContent-Type:".$file_type.";\n\tname=\"$file_name\"\nContent-Transfer-Encoding: base64\nContent-Disposition: inline;\n\tfilename=\"$file_name\"\n\n$data_encode";
        }
    }

/*= La préparation est terminée, nous envoyons le message =*/
    $hold_from = "From: ".$mail_exp."\n".$MIME."\n";

    $hold_message = $startMsg.$hold_message.$ending;

    mail( $mail_dest, $mail_subject, $hold_message, $hold_from );
}
?>

This code is used here: http://www.ansb-brasil.org/trab_conosco/trab_conosco.php

0

You need to convert the file to a file for a Swiftmailer mime type Swift_Mime_MimeEntity type. CUploadedFile::getInstanceByName('fileupload') Returns to Cuploadedfile class, which Swiftmailer does not know how to handle. More information on Swift attachments here.

I didn’t test it, but you’ll need to do something like this:

$uploadedFile = CUploadedFile::getInstanceByName('fileupload'); // get the CUploadedFile
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName); // create a Swift Attachment
$this->email->attach($swiftAttachment); // now attach the correct type

Good luck

  • How would I use this getInstanceByName('fileupload') in my code? Sorry but I have very little practice in PHP. I had already seen this solution in the English version...

  • da uma pesquisada http://www.yiiframework.com/doc/api/1.0/CUploadedFile ali Voce finds a little more information ... or even in the other links I sent you

  • I understood quite well the information in these links that you sent me, but I want to send an attachment that is uploaded by the contact form. I don’t want to send a file that is already on the server, nor do I want to upload to the server first, and then attach the file to the email. I want the user to define which file to send, and that file to be sent by email along with the other contact information, without having to stay on the server.

  • first Voce moves to the server, sends the email, then deletes it simple

  • There’s no way to do that directly?

  • I never had to do it directly ... I think there is no way but so the file goes up to a tmp sends straight from there and there is no scheme

  • 1

    No need to delete: when you use an input file, the file is saved to the server but will be automatically destroyed when the script will end (which is why we should copy it using move_uploaded_file to use it later). So if, within your script, you send the received document directly, without user move_uploaded_file() at the end of the script, this document will disappear.

  • perfect @Peter

Show 3 more comments

Browser other questions tagged

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