Ver Mensaje Individual
  #1 (permalink)  
Antiguo 31/03/2015, 06:10
conik500
 
Fecha de Ingreso: noviembre-2014
Ubicación: Granada
Mensajes: 7
Antigüedad: 10 años, 5 meses
Puntos: 1
Exclamación Enviar adjunto AJAX y PHPMailer

Hola, tengo un formulario HTML el cual, al darle a un boton, llama a una función de Javascript que recoge los datos del form, y los envía a un fichero PHP que envía los datos con PHPMailer. Todo esto iba vien, hasta que he puesto para que se puedan enviar adjuntos un input type file. Al principio,en la función Send() de AJAX escribía cada dato de la siguiente forma "dato1="+dato1+"&dato2", etc. Ahora, para mandar los adjuntos, uso la función FormData de la siguiente forma.

Formulario HTML:
Código HTML:
<form name="form" action="#" id='file-form'>
Tema:<br>
<select name="correo">
<option>1</option>
<option>2</option>
</select>

<br><br>
Asunto:<br>
<input type="text" name="asunto">
<br><br>

Cuerpo:<br>
<textarea name="cuerpo" id="cuerpo" style="height: 150px; resize: none;"></textarea>

<input type="file" id='file-select'>
</form>
<br>
<button class="boton" onclick="javascript:enviarcorreo();">Enviar</button> 
La función JS:

Código Javascript:
Ver original
  1. function enviarcorreo(){
  2.  
  3.   asunto=document.form.asunto.value;
  4.   cuerpo=document.form.cuerpo.value;
  5.   correo=document.form.correo.value;
  6.  
  7.  
  8.   var form = document.getElementById('file-form');
  9.   var fileSelect = document.getElementById('file-select');
  10.  
  11.  
  12.   var files = fileSelect.files;
  13. //Loop through each of the selected files.
  14.  
  15.   for (var i = 0; i < files.length; i++) {
  16.     var file = files[i];
  17.  
  18.     formData.append('adjunto', file, file.name);
  19.   }
  20.  
  21.  
  22.  
  23.  
  24.  
  25.   if (cuerpo=='' || asunto==''){
  26.      alert('Debe rellenar todos los campos');
  27.      
  28.   }else{
  29.      
  30.  correoe = '[email protected]';
  31.  filtroe = '[FILTRO]';
  32.  
  33.    
  34.        
  35.        
  36.         ajax6=objetoAjax();
  37.  
  38.         ajax6.open("POST", "mail2.php",true);
  39.  
  40.         ajax6.onreadystatechange=function(){
  41.            
  42.             if (ajax6.readyState==4) {
  43.                
  44.                
  45.                 var valor = ajax6.responseText;
  46.  
  47.                
  48.                        if (valor==1){
  49.                            window.location ="index.php";
  50.                        }else{
  51.                            alert(valor);
  52.                        }
  53.                
  54.                
  55.  
  56.             }
  57.         }
  58.             ajax6.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  59.            
  60.             var formData = new FormData();
  61.            
  62.             formData.append("asunto", filtroe + " - " + asunto);
  63.             formData.append("cuerpo", cuerpo);
  64.             formData.append("correo", correoe);
  65.            
  66.             ajax6.send(formData);
  67.              
  68.   }
  69. }

Y mail2.php:
Código PHP:
<?php
require ('PHPMailer/class.phpmailer.php');
require (
"PHPMailer/class.smtp.php");

$mail             = new PHPMailer();
$body             $_POST["cuerpo"];

$mail->IsSMTP(); // telling the class to use SMTP

$mail->Host       "MI HOST"// SMTP server

$mail->From "CORREO DESDE EL QUE ENVIA";

$mail->FromName "NOMBRE";

$mail->Subject $_POST["asunto"];

$mail->AltBody "Cuerpo alternativo 
    para cuando el visor no puede leer HTML en el cuerpo"


$mail->MsgHTML($body);


$mail->AddAddress($_POST["correo"], "Elecciones");

if (isset(
$_FILES['adjunto']) &&   $_FILES['adjunto']['error'] == UPLOAD_ERR_OK) {
    
$mail->AddAttachment($_FILES['adjunto']['tmp_name'],
                         
$_FILES['adjunto']['name']);

}
// si el SMTP necesita autenticación
$mail->SMTPAuth true;

// credenciales usuario
$mail->Username "USUARIO";
$mail->Password "CONTRASEÑA"
$mail->CharSet'UTF-8';

if(!
$mail->Send()) {
echo 
"Error al enviar el mensaje: " $mail*>ErrorInfo;
} else {

echo 
"1";
}
?>