Send attachment by PHP, but with HTML format

-1

I am creating an application where the following code is the contact part, where the user adds his name, email, selects a charge, telephone and message. I just added a field to attach file, but I would like to know what the error is inside the code , since I only receive the user's data, but I do not receive any file to my mail. I do the tests from a server

Here I leave the PHP code.

<?php

//Variables para los campos de texto
$nombre = strip_tags($_POST["nombre"]);
$email = strip_tags($_POST["email"]);
$cargo = strip_tags($_POST["cargo"]);
$telefono = strip_tags($_POST["telefono"]);
$mensaje = strip_tags($_POST["mensaje"]);

//Variables para los datos del archivo
$nameFile = $_FILES['archivo']['name'];
$sizeFile = $_FILES['archivo']['size'];
$typeFile = $_FILES['archivo']['type'];
$tempFile = $_FILES['archivo']['tmp_name'];

$content = chunk_split(base64_encode(file_get_contents($_FILES['archivo']['tmp_name'])));

$fecha = time();
$fechaFormato = date('d/m/y', $fecha);

$corredoDestino = '[email protected]';

$eol = "\r\n";
//asunto del correo
$titulo = "Mensaje de la web recibido";

// -> mensaje en formato Multipart MIME
$cabecera = "MIME-VERSION: 1.0" .$eol;
$cabecera .= "Content-type: multipart/mixed; boundary=\"" .$fecha. "\"" .$eol;
$cabecera .= "Content-Transfer-Encoding: 7bit" .$eol;
$cabecera .= "From: {$mail}";

//Primera parte del cuerpo del mensaje
$cuerpo = "--=C=T=E=C=" .$eol;
$cuerpo .= "Content-type: text/plain; charset=utf-8" .$eol;
$cuerpo .= "Content-Transfer-Encoding: 8bit" .$eol;
$cuerpo .= $eol; //línea vacía
$cuerpo .= "Haz recibido un mensaje atravez de la página solmit.net" .$eol;
$cuerpo .= "Mensaje enviado por: " .$nombre. "" .$eol;
$cuerpo .= "ponerse en contacto con: " .$email. "" .$eol;
$cuerpo .= "Selecciono el cargo de: " .$cargo. "" .$eol;
$cuerpo .= "El teléfono de la persona es: " .$telefono. "" .$eol;
$cuerpo .= "Mensaje: " .$mensaje. "" .$eol;
$cuerpo .= $eol;
$cuerpo .= " Enviado el: " .$fechaFormato. "" .$eol;
$cuerpo .= $eol;

// -> Segunda parte del mensaje (archivo adjunto)
    // -> encabezado de la parte
$cuerpo .= "--=C=T=E=C=" .$eol;
$cuerpo .= "Content-Type: application/octet-stream; name=\"" .$nameFile. "\"" .$eol;
$cuerpo .= "Content-Transfer-Encoding: base64" .$eol;
$cuerpo .= "Content-Disposition: attachment" .$eol;
$cuerpo .= "filename= " .$nameFile. "" .$eol;
$cuerpo .= $eol; //línea vacía

// $fp = fopen($tempFile, "rb");
// $file = fread($fp, $sizeFile);
// $file = chunk_split(base64_encode($file));

// $cuerpo .= $file .$eol;
// $cuerpo .= $eol; //linea vacia
// //Delimitador de final del mensaje.
// $cuerpo .= "--=C=T=E=C=--" .$eol;

//Enviar el correo
$envio = mail($corredoDestino, $titulo, $cuerpo, $cabecera);

if($envio) {
    header('Location: index.html');
} else {
    echo "Error de envío";
}

? >

This is the HTML part of the Form.

<form method="post" action="enviar.php" enctype="multipart/form-data">
                                <div class="form-group">

                                    <input type="text" name="nombre" class="form-control" id="nombre" placeholder="NOMBRE" required>
                                </div>
                                <div class="form-group">

                                    <input type="email" name="email" class="form-control" id="correo" placeholder="CORREO" required>
                                </div>
                                <div class="form-group">

                                    <select class="form-control" name="cargo" required>
                                        <option value="" disabled selected>Seleccionar Cargo</option>
                                        <option value="Programador Web C#.Net">Programador Web C#.Net</option>
                                        <option value="Programador Senior Web en C#.Net Bilingue">Programador Senior Web en C#.Net Bilingue</option>
                                      </select>
                                </div>
                                <div class="form-group">

                                    <input type="text" name="telefono" class="form-control" id="telefono" placeholder="TELÉFONO" required>
                                </div>
                                <div class="form-group">

                                    <textarea class="form-control" rows="5" name="mensaje" placeholder="Escriba su mensaje" required></textarea>
                                </div>

                                <div class="label-form" style="text-align: center; font-size: 24px;">
                                    <p class="p">Adjuntar CV:</p>
                                </div>
                                <div class="style-archivo">
                                    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                    <input type="file" name="archivo" id="archivo" placeholder="" size="30" />
                                </div>

                                <button class="btn-primary-f" type="submit">Enviar</button>
                                <p class="p">+ Información llámenos:</br> <span>0505050505</span></p>

    
asked by Dominic A.Villanueva 10.11.2017 в 01:04
source

2 answers

0

In the Simon Mokhele's response in Stack Overflow in English , you can find an example of how a file can be added as an attachment to an email with mail . This is your code:

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
    return true; // Or do something here
} else {
  return false;
}

Now we can adapt it to your particular case:

  

CAUTION : I have not been able to test this code on a server so I can not guarantee 100% that it works. Writing the values on the screen, it seems that there should be no problem, but when I upload it to a server it has given me a bug (not related to the code, but with the server's own configuration).

     

ALSO : The original code you share may suffer XSS attacks by failing to process user entries correctly. I have not corrected those errors, but I recommend that you read about XSS and how to avoid it in PHP.

<?php
    $nombre = isset( $_POST['nombre']) ? $_POST['nombre'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $cargo = isset($_POST['cargo']) ? $_POST['cargo'] : '';
    $telefono = isset($_POST['telefono']) ? $_POST['telefono'] : '';
    $mensajeusuario = isset($_POST['mensaje']) ? $_POST['mensaje'] : '';

    $fichero = $_FILES["archivo"]["tmp_name"];
    $contenidofichero = file_get_contents( $fichero );
    $contenidoficheor = chunk_split(base64_encode($contenidofichero));
    $uid = md5(uniqid(time()));
    $nombrefichero = basename($fichero);

    $fecha = time();
    $fechaFormato = date('d/m/y h:i:s', $fecha);

    //Cpmtemtodp del mensaje
    $titulo = "Mensaje de la web recibido";
    $contenido = '
                    <html>
                        <head>
                            <title>' .$titulo. '</title>
                        </head>
                        <body>
                            <h2>Haz recibido un mensaje atravez de la página</h2>
                            <p>Mensaje enviado por: <strong>' .$nombre. '</strong></p>
                            <p>ponerse en contacto con: <strong>' .$email. ',</strong></p>
                            <p>Selecciono el cargo de: <strong>' .$cargo. ',</strong></p>
                            <p>El teléfono de la persona es: <strong>' .$telefono. ',</strong></p>
                            <p>Mensaje: '.$mensajeusuario.'</p>
                            <hr>
                            <p>Enviado el: <strong>' .$fechaFormato. '</strong></p>
                        </body>
                    </html>';

    //Configuración de los encabezados
    $headers = "MIME-Version: 1.0 \r\n";
    $headers .= "Content-type: multipart/mixed; boundary=\"".$uid."\"\r\n";

    // primero ponemos el mensaje y luego el archivo adjunto, cerrando con el serparador
    $mensaje = "--".$uid."\r\n";
    $mensaje .= "Content-type:text/plain; charset=utf-8\r\n";
    $mensaje .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $mensaje .= $contenido."\r\n\r\n";

    $mensaje = "--".$uid."\r\n";
    $mensaje .= "Content-Type: application/octet-stream; name=\"".$nombrefichero."\"\r\n";
    $mensaje .= "Content-Transfer-Encoding: base64\r\n";
    $mensaje .= "Content-Disposition: attachment; 
    filename=\"".$nombrefichero."\"\r\n\r\n";
    $mensaje .= $contenidofichero."\r\n\r\n";
    $mensaje .= "--".$uid."--";

    $para = '[email protected]';
    $envio = mail($para, $titulo, $mensaje, $headers);

    if($envio) {
        $miresultado = '<h4>El correo ha sido enviado! Gracias por ponerse en contacto con nosotros.</h4>';
    } else {
        $miresultado = '<h4>No se envio el correo.</h4>';
    }

    //header('Location: index.html');
    echo $miresultado;
?>
    
answered by 10.11.2017 в 21:02
0

Thanks for the contribution I was testing from a server, and you are right not to process the user correctly I was investigating more and I found this code with type = text / plain. This piece of code I was testing and it turns out that if you send the file everything is correct but it does not send me the body of the message, rather the user's information. I would like to know what I am doing wrong in this part of the code

<?php

    //Variables para los campos de texto
    $nombre = strip_tags($_POST["nombre"]);
    $email = strip_tags($_POST["email"]);
    $cargo = strip_tags($_POST["cargo"]);
    $telefono = strip_tags($_POST["telefono"]);
    $mensaje = strip_tags($_POST["mensaje"]);

    //Variables para los datos del archivo
    $nameFile = $_FILES['archivo']['name'];
    $sizeFile = $_FILES['archivo']['size'];
    $typeFile = $_FILES['archivo']['type'];
    $tempFile = $_FILES['archivo']['tmp_name'];

    $fecha = time();
    $fechaFormato = date('d/m/y', $fecha);

    $corredoDestino = '[email protected]';

    //asunto del correo
    $titulo = "Mensaje de la web recibido";

    // -> mensaje en formato Multipart MIME
    $cabecera = "MIME-VERSION: 1.0\r\n";
    $cabecera .= "Content-type: multipart/mixed;";
    $cabecera .= "boundary=\"=C=T=E=C=\"\r\n";
    $cabecera .= "From: {$mail}";

    //Primera parte del cuerpo del mensaje
    $cuerpo = "--=C=T=E=C=\r\n";
    $cuerpo .= "Content-type: text/plain";
    $cuerpo .= "charset=utf-8\r\n";
    $cuerpo .= "Content-Transfer-Encoding: 8bit\r\n";
    $cuerpo .= "\r\n"; //línea vacía
    $cuerpo .= "Haz recibido un mensaje atravez de la página solmit.net \r\n";
    $cuerpo .= "Mensaje enviado por: " .$nombre. "\r\n";
    $cuerpo .= "ponerse en contacto con: " .$email. "\r\n";
    $cuerpo .= "Selecciono el cargo de: " .$cargo. "\r\n";
    $cuerpo .= "El teléfono de la persona es: " .$telefono. "\r\n";
    $cuerpo .= "Mensaje: " .$mensaje. "\r\n";
    $cuerpo .= "\r\n";
    $cuerpo .= " Enviado el: " .$fechaFormato. "\r\n";
    $cuerpo .= "\r\n";

    // -> Segunda parte del mensaje (archivo adjunto)
        // -> encabezado de la parte
    $cuerpo .= "--=C=T=E=C=\r\n";
    $cuerpo .= "Content-Type: application/octet-stream; ";
    $cuerpo .= "name=" .$nameFile. "\r\n";
    $cuerpo .= "Content-Transfer-Encoding: base64\r\n";
    $cuerpo .= "Content-Disposition: attachment; ";
    $cuerpo .= "filename= " .$nameFile. "\r\n";
    $cuerpo .= "\r\n"; //línea vacía

    $fp = fopen($tempFile, "rb");
    $file = fread($fp, $sizeFile);
    $file = chunk_split(base64_encode($file));

    $cuerpo .= "$file\r\n";
    $cuerpo .= "\r\n"; //linea vacia
    //Delimitador de final del mensaje.
    $cuerpo .= "--=C=T=E=C=--\r\n";

    //Enviar el correo
    $envio = mail($corredoDestino, $titulo, $cuerpo, $cabecera);

    if($envio) {
        header('Location: index.html');
    } else {
        echo "Error de envío";
    }
?>
    
answered by 10.11.2017 в 21:42