Foros del Web » Creando para Internet » HTML »

Adjuntar Archivo a un correo desde un Form

Estas en el tema de Adjuntar Archivo a un correo desde un Form en el foro de HTML en Foros del Web. El problema que tengo es que no se visualiza en archivo adjunto al correo, los demás espacios llegan con su respectiva respuesta Adjunto el codigo ...
  #1 (permalink)  
Antiguo 27/06/2011, 12:07
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Adjuntar Archivo a un correo desde un Form

El problema que tengo es que no se visualiza en archivo adjunto al correo, los demás espacios llegan con su respectiva respuesta Adjunto el codigo fuente.

HTML
<form id="formElem" name="formElem" action="enviar.php" method="post" enctype="multipart/form-data">

name="form">
<fieldset class="step">
<legend>Datos Personales</legend>

<p>
<label for="name">*Primer Nombre</label>
<input type="text" name="Nombre" id="Nombre" value="" />

</p>
<p>
<label for="SegundoNombre">Segundo Nombre:</label>
<input type="text" name="SegundoNombre" id="SegundoNombre" value="" />
</p>
<p>
<label for="PrimerApellido">* Primer Apellido: </label>
<input type="text" name="PrimerApellido" id="PrimerApellido" value="" />
</p>


<p>
<label for="SegundoApellido">Segundo Apellido: </label>
<input type="text" name="SegundoApellido" id="SegundoApellido" value="" />
</p>

<p>
<label for="NúmerodeIdentificación:">* Número de Identificación:</label>
<input type="text" name="NúmerodeIdentificación" id="NúmerodeIdentificación" value="" />
</p>
<p>
<label for="archivo">Subir Archivo* <br /> (Solamente PDF) <br /> </label>
<input name="archivo" type="file" id="archivo" /> <br>
</fieldset>
<fieldset class="step">

<legend>Enviar</legend>
<p class="submit"><input name="button2" type="submit" id="button2" value="Enviar" /></p></fieldset></form></div>



El PHP ES el siguiente


<?php


$Nombre = $_POST['Nombre'];
$SegundoNombre = $_POST['SegundoNombre'];
$PrimerApellido = $_POST['PrimerApellido'];
$SegundoApellido = $_POST['SegundoApellido'];
$NúmerodeIdentificación = $_POST['NúmerodeIdentificación'];

$file = $_POST['file'];



$header = 'De parte de: ' . $Nombre . " \r\n";
$header .= "X-Mailer: PHP/" . phpversion() . " \r\n";
$header .= "Mime-Version: 1.0 \r\n";
$header .= "Content-Type: text/plain";


$mensaje = "Nombre: " . $Nombre . " \r\n";
$mensaje .= "Segundo Nombre : " . $SegundoNombre . " \r\n" ;
$mensaje .= "Primer Apellido : " . $PrimerApellido . " \r\n" ;
$mensaje .= "Segundo Apellido: " . $SegundoApellido . " \r\n" ;
$mensaje .= "Número de Identificación: " . $NúmerodeIdentificación . " \r\n" ;

$mensaje .= "Archivo Adjunto: ". $file . " \r\n" ;
$aleatorio = rand();
$nombreoriginal= explode ('.', $_FILES['file']['name']);
$nuevonombre=$nombreoriginal[0].'-'.$aleatorio.'.'.$ext;
copy($_FILES['file']['tmp_name'],'archivos/'.$nuevonombre);

$mensaje .= "Enviado el " . date('d/m/Y', time());
$para = '[email protected]';
$asunto = 'Contacto Telemeca';
mail($para, $asunto, utf8_decode($mensaje), $header);


echo 'Mensaje enviado correctamente';




?>
  #2 (permalink)  
Antiguo 27/06/2011, 15:00
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Adjuntar Archivo a un correo desde un Form

Necesitas los hedaers apropiados en el email
Content-Type: multipart/mixed

Acá te dejo un link (en ingés) dónde está mejor explicado
http://www.webcheatsheet.com/PHP/sen...attachment.php

Hay otras variantes, una de ellas utilizando la clase phpmailer, aca una guia (en español)
http://blog.unijimpe.net/enviar-email-con-adjuntos/

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.

Última edición por emprear; 27/06/2011 a las 15:01 Razón: link erroneo
  #3 (permalink)  
Antiguo 27/06/2011, 15:28
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Adjuntar Archivo a un correo desde un Form

Cita:
Iniciado por emprear Ver Mensaje
Necesitas los hedaers apropiados en el email
Content-Type: multipart/mixed

Acá te dejo un link (en ingés) dónde está mejor explicado
[url]http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php[/url]

Hay otras variantes, una de ellas utilizando la clase phpmailer, aca una guia (en español)
[url]http://blog.unijimpe.net/enviar-email-con-adjuntos/[/url]

Saludos
Muchas gracias amigo, en otras palabras tengo que montarlo todo de nuevo utilizando phpmailer.
Ademas te informo que estoy Utilizando Jquery. el link del sitio es el siguiente

http://www.ridesupercompro.com/NuevaCarpeta/index.html
  #4 (permalink)  
Antiguo 27/06/2011, 15:58
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Adjuntar Archivo a un correo desde un Form

Bueno, no se si debas montarlo todo de vuelta, quizás se pueda adaptar, además el ejemplo del primer link no usa la clase phpmailer.

Por que no pruebas de hacer una script de prueba para verificar el funcionamiento de una y otra, y despues adaptas a tu script.

Lo mas importante sería que en

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));

reemplaces el valor attachment.zip por el de tu upload, que segun parece de tu form, es un pdf

El jQuery no veo porque deba de interferir

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #5 (permalink)  
Antiguo 27/06/2011, 16:22
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Adjuntar Archivo a un correo desde un Form

Gracias lo voy a intentar porq ya llevo bastante con eso y mas bien ya no me entra en la cabeza. Estoy como cansadooo
  #6 (permalink)  
Antiguo 27/06/2011, 16:39
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Adjuntar Archivo a un correo desde un Form

mirá. hice esto, copie la script del primer link, reemplacé en la primera linea
$to = '[email protected]'; por mi email, y en $headers = "From: [email protected]\r\nReply-To: [email protected]";
puse una dirección válida, puse en la misma carpeta un archivo con nombre attachment.zip, y me llegó perfecto, asi que solo tenes que integrala con tus

$Nombre = $_POST['Nombre'];
$SegundoNombre = $_POST['SegundoNombre'];
$PrimerApellido = $_POST['PrimerApellido'];
$SegundoApellido = $_POST['SegundoApellido'];
$NúmerodeIdentificación = $_POST['NúmerodeIdentificación'];

$file = $_POST['file'];


Miá tambien, que el ejemplo te manda dos textos, uno en txt/plain y otro en html, todo en el mismo mensaje, supongho habria que poner ó uno u otro
Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #7 (permalink)  
Antiguo 27/06/2011, 16:53
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Adjuntar Archivo a un correo desde un Form

Amigo lo que hice fue lo siguiente:



<?php
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
//send the email
$Nombre = $_POST['Nombre'];
$SegundoNombre = $_POST['SegundoNombre'];
$PrimerApellido = $_POST['PrimerApellido'];
$SegundoApellido = $_POST['SegundoApellido'];
$NúmerodeIdentificación = $_POST['NúmerodeIdentificación'];
$TipodeIdentificación = $_POST['TipodeIdentificación'];
$Permisodeconducir = $_POST['Permisodeconducir'];
$Nacionalidad = $_POST['Nacionalidad'];
$PaísdeResidencia = $_POST['PaísdeResidencia'];
$CiudaddeResidencia = $_POST['CiudaddeResidencia'];
$email = $_POST['email'];
$telefono1 = $_POST['telefono1'];
$telefono2 = $_POST['telefono2'];
$GradoAcadémico = $_POST['GradoAcadémico'];
$OtroEstudio = $_POST['OtroEstudio'];
$PrimerIdioma1 = $_POST['PrimerIdioma1'];
$PrimerIdioma2 = $_POST['PrimerIdioma2'];
$SegundoIdioma1 = $_POST['SegundoIdioma1'];
$SegundoIdioma2 = $_POST['SegundoIdioma2'];
$TercerIdioma1 = $_POST['TercerIdioma1'];
$TercerIdioma2 = $_POST['TercerIdioma2'];
$Herramienta0 = $_POST['Herramienta1'];
$Herramienta1 = $_POST['Herramienta2'];
$Herramienta2 = $_POST['Herramienta3'];
$Herramienta3 = $_POST['Herramienta4'];
$a1 = $_POST['Recepción'];
$a2 = $_POST['ÁreaAdministrativa'];
$a3 = $_POST['Proveeduría'];
$a4 = $_POST['Logística'];
$a5 = $_POST['Contabilidad'];
$a6 = $_POST['Planillas'];
$a7 = $_POST['PresupuestosElectromecánicos'];
$a8 = $_POST['BodegasElectromecánicas'];
$a9 = $_POST['RecursosHumanos'];
$a10 = $_POST['IngenieríaElectromecánica'];
$a11 = $_POST['Mensajería'];
$a12 = $_POST['Electricistas'];
$a13 = $_POST['Fontaneros'];
$ExperienciaLaboral = $_POST['ExperienciaLaboral'];
$introduccion = $_POST['introduccion'];
$file = $_POST['file'];

//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>


Y no me sirvió, solo me llego Hello World!\n\nThis is my first mail.
  #8 (permalink)  
Antiguo 27/06/2011, 17:26
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Adjuntar Archivo a un correo desde un Form

Amigoo ahora lo hice de esta manera:
<?php
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attac hment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
$file = ob_get_clean();
$Nombre = ob_get_clean();
$SegundoNombre = ob_get_clean();
$PrimerApellido = ob_get_clean();
$SegundoApellido = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $file, $Nombre, $SegundoNombre,
$PrimerApellido,
$SegundoApellido, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>


Pero al final de enviarlo me tira el siguiente error:

Warning: file_get_contents(attachment.zip) [function.file-get-contents]: failed to open stream: No such file or directory in /var/www/web101/web/NuevaCarpeta/enviar.php on line 16
Mail failed
  #9 (permalink)  
Antiguo 27/06/2011, 17:46
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Adjuntar Archivo a un correo desde un Form

Marotto
Yo te dije que tenias que adaptarla,

el archivo del ejemplo se llama attachment.zip, pero no está subido con un form, simplemente ya esta en el server, en tu primer post habias hecho algo asi

$nombreoriginal= explode ('.', $_FILES['file']['name']);
$nuevonombre=$nombreoriginal[0].'-'.$aleatorio.'.'.$ext;
copy($_FILES['file']['tmp_name'],'archivos/'.$nuevonombre);


ese deberia ser el archivo que se sube, y ese es el nombre que deberias poner en la script, y por supuesto que las rutas coincidan


Se entiende

Proba la script como esta, solo cambia el email y pone un archivo de ese nombre en la misma carpeta, y fijate como te llega, analizalo y vas a ver como es

Acabo de mandarte con la script un email con un adjunto

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #10 (permalink)  
Antiguo 28/06/2011, 08:57
 
Fecha de Ingreso: junio-2011
Ubicación: San Jose, Costa Rica
Mensajes: 52
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Adjuntar Archivo a un correo desde un Form

Cita:
Iniciado por emprear Ver Mensaje
Marotto
Yo te dije que tenias que adaptarla,

el archivo del ejemplo se llama attachment.zip, pero no está subido con un form, simplemente ya esta en el server, en tu primer post habias hecho algo asi

$nombreoriginal= explode ('.', $_FILES['file']['name']);
$nuevonombre=$nombreoriginal[0].'-'.$aleatorio.'.'.$ext;
copy($_FILES['file']['tmp_name'],'archivos/'.$nuevonombre);


ese deberia ser el archivo que se sube, y ese es el nombre que deberias poner en la script, y por supuesto que las rutas coincidan


Se entiende

Proba la script como esta, solo cambia el email y pone un archivo de ese nombre en la misma carpeta, y fijate como te llega, analizalo y vas a ver como es

Acabo de mandarte con la script un email con un adjunto

Saludos
Muchas gracias por la ayudaaa. La verdad es que no le llego yo apenas estoy utilizando PHP pero ya quede botadoo Graciass

Etiquetas: correo, formulario
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:34.