2011-12-12 21 views
7

Bien chicos, este es mi primer hilo, y lo he buscado en línea pero sin suerte. Estoy haciendo una pasantía y estoy trabajando en un proyecto que me obliga a crear una página web que genera un archivo pdf cuando un usuario envía su información. Tan pronto como un cliente hace clic en el botón de envío, 3 cosas tienen que suceder:Enviando un correo electrónico con archivos adjuntos en PDF usando PHP

  1. Almacenar la información a la base de datos (hecho),
  2. Envía el personal de un correo electrónico con la nueva información del cliente (hecho), y
  3. Envíe al cliente un mensaje de "mensaje de agradecimiento" con un archivo adjunto en PDF (no funciona).

Es decir, el cliente recibirá un correo electrónico, pero cuando él/ella abre el archivo PDF, me sale el siguiente mensaje de error:

"Acrobat podría no oen 'nombre_archivo', ya que es o bien no es un tipo de archivo compatible o porque el archivo se ha dañado (por ejemplo, se envió como un archivo adjunto de correo electrónico y no se decodificó correctamente) ... "

Tenga en cuenta que esta es mi primera vez haciendo un proyecto para crear un archivo PDF adjunto. Si alguien pudiera ayudarme a resolver este problema, sería genial. ¡Gracias!

Aquí está mi código:

<?php 
// once there are no errors, as soon as the customer hits the submit button, it needs to send an email to the staff with the customer information 
     $msg = "Name: " .$_POST['name'] . "\n" 
      ."Email: " .$_POST['email'] . "\n" 
      ."Phone: " .$_POST['telephone'] . "\n" 
      ."Number Of Guests: " .$_POST['numberOfGuests'] . "\n" 
      ."Date Of Reunion: " .$_POST['date']; 
     $staffEmail = "staffinfo"; 

     mail($staffEmail, "You have a new customer", $msg); // using the mail php function to send the email. mail(to, subject line, message) 

     //once the customer submits his/her information, he/she will receive a thank you message attach with a pdf file. 
     $pdf=new FPDF(); 
     $pdf->AddPage(); 
     $pdf->SetFont("Arial", "B", 16); 
     $pdf->Cell(40, 10, "Hello World!"); 

     // email information 
     $to = $_POST['email']; 
     $from = $staffEmail; 
     $subject = "Thank you for your business"; 
     $message = "Thank you for submitting your information!"; 

     // a random hash will be necessary to send mixed content 
     $separator = md5(time()); 

     // carriage return type (we use a PHP end of line constant) 
     $eol = PHP_EOL; 

     // attachment name 
     $filename = "yourinformation.pdf"; 

     // encode data (puts attachment in proper format) 
     $pdfdoc = $pdf->Output("", "S"); 
     $attachment = chunk_split(base64_encode($pdfdoc)); 

     // encode data (multipart mandatory) 
     $headers = "From: ".$from.$eol; 
     $headers .= "MIME-Version: 1.0".$eol; 
     $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol; 
     $headers .= "Content-Transfer-Enconding: 7bit".$eol; 
     $headers .= "This is a MIME encoded message.".$eol.$eol; 

     // message 
     $headers .= "--".$separator.$eol; 
     $headers .= "Content-Type: text/html; charsrt=\"iso-8859-1\"".$eol; 
     $headers .= $message.$eol.$eol; 

     // attachment 
     $headers .= "--".$separator.$eol; 
     //$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
     $headers .= "Content-Type: application/zip; name=\"".$filename."\"".$eol; 
     $headers .= "Content-Transfer-Encoding: base64".$eol; 
     $headers .= "Content-Disposition: attachment".$eol.$eol; 
     $headers .= $attachment.$eol.$eol; 
     $headers .= "--".$separator."--"; 

     // send message 
     mail($to, $subject, $message, $headers); 

    } 
} 
?> 
+0

me di cuenta de que tiene application/zip. Pruebe la aplicación/pdf en su lugar. – Raisen

+0

Lo hice también, pero no funcionará. –

+0

Aún no se ha pensado bien en ello, pero IIOL el eol para encabezados MIME siempre es "\ r \ n", el valor real en 'PHP_EOL' varía según el SO; eso podría poner a una llave en las obras en tus $ headers var; aunque de acuerdo con la especificación debe ser tolerante: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html (19.3) – CD001

Respuesta

3
// once there are no errors, as soon as the customer hits the submit button, it needs to send an email to the staff with the customer information 
     $msg = "Name: " .$_POST['name'] . "\n" 
      ."Email: " .$_POST['email'] . "\n" 
      ."Phone: " .$_POST['telephone'] . "\n" 
      ."Number Of Guests: " .$_POST['numberOfGuests'] . "\n" 
      ."Date Of Reunion: " .$_POST['date']; 
     $staffEmail = "staffemail"; 

     mail($staffEmail, "You have a new customer", $msg); // using the mail php function to send the email. mail(to, subject line, message) 

     //once the customer submits his/her information, he/she will receive a thank you message attach with a pdf file. 
     // creating a pdf file 
     $pdf_filename = tempnam(sys_get_temp_dir(), "pdf"); 
     $pdf=new FPDF(); 
     $pdf->AddPage(); 
     $pdf->SetFont("Arial", "B", 16); 
     $pdf->Cell(40, 10, "Title"); 
     $pdf->Ln(); 
     $pdf->SetFont("Arial", "", 12); 
     $pdf->Cell(15, 10, "Name:"); 
     $pdf->SetFont("Arial", "I", 12); 
     $pdf->Cell(15, 10, $_POST['name']); 
     $pdf->Ln(); 
     $pdf->SetFont("Arial", "", 12); 
     $pdf->Cell(15, 10, "Email:"); 
     $pdf->SetFont("Arial", "I", 12); 
     $pdf->Cell(15, 10, $_POST['email']); 
     $pdf->Ln(); 
     $pdf->SetFont("Arial", "", 12); 
     $pdf->Cell(15, 10, "Phone:"); 
     $pdf->SetFont("Arial", "I", 12); 
     $pdf->Cell(15, 10, $_POST['telephone']); 
     $pdf->Ln(); 
     $pdf->SetFont("Arial", "", 12); 
     $pdf->Cell(40, 10, "Number of Guests:"); 
     $pdf->SetFont("Arial", "I", 12); 
     $pdf->Cell(40, 10, $_POST['numberOfGuests']); 
     $pdf->Ln(); 
     $pdf->SetFont("Arial", "", 12); 
     $pdf->Cell(40, 10, "Date Of Reunion:"); 
     $pdf->SetFont("Arial", "I", 12); 
     $pdf->Cell(40, 10, $_POST['date']); 
     // if file doesn't exists or if it is writable, create and save the file to a specific place 
     if(!file_exists($pdf_filename) || is_writable($pdf_filename)){ 
      $pdf->Output($pdf_filename, "F"); 
     } else { 
      exit("Path Not Writable"); 
     } 

     // using the phpmailer class 
     // create a new instance called $mail and use its properties and methods. 
     $mail = new PHPMailer(); 
     $staffEmail = "staffemail"; 
     $mail->From = $staffEmail; 
     $mail->FromName = "name"; 
     $mail->AddAddress($_POST['email']); 
     $mail->AddReplyTo($staffEmail, "name"); 

     $mail->AddAttachment($pdf_filename); 
     $mail->Subject = "PDF file attachment"; 

     $mail->Body = "message!"; 

     // if mail cannot be sent, diplay error message 
     //if(!$mail->Send()){ 
      //echo "<div id=\"mailerrors\">Message could not be sent</div>"; 
      //echo "<div id=\"mailerrors\">Mailer Error: " . $mail->ErrorInfo . "</div>"; 
     //} else { // else...if mail is sent, diplay sent message 
      //echo "<div id=\"mailerrors\">Message sent</div>"; 
     //} 

     // delete the temp file 
     unlink($pdf_filename); 
    } 
}  
+0

¡Este es mi código final, y funciona perfectamente! –

+1

Este es un comentario tardío, pero probablemente deba usar 'tempnam' para generar un nombre de archivo único, de modo que no se arriesgue a tener un problema con dos clientes que aciertan al script de una vez. – yakatz

0

Prueba esto:

<?php 

    // once there are no errors, as soon as the customer hits the submit button, 
    // it needs to send an email to the staff with the customer information 
    $msg = "Name: " .$_POST['name'] . "\n" 
     . "Email: " .$_POST['email'] . "\n" 
     . "Phone: " .$_POST['telephone'] . "\n" 
     . "Number Of Guests: " .$_POST['numberOfGuests'] . "\n" 
     . "Date Of Reunion: " .$_POST['date']; 
    $staffEmail = "staffinfo"; 
    mail($staffEmail, "You have a new customer", $msg); 

    // once the customer submits his/her information, he/she will receive a thank 
    // you message attach with a pdf file. 
    $pdf = new FPDF(); 
    $pdf->AddPage(); 
    $pdf->SetFont("Arial", "B", 16); 
    $pdf->Cell(40, 10, "Hello World!"); 

    // email information 
    $to = $_POST['email']; 
    $from = $staffEmail; 
    $subject = "Thank you for your business"; 
    $message = "Thank you for submitting your information!"; 

    // a random hash will be necessary to send mixed content 
    $separator = '-=-=-'.md5(microtime()).'-=-=-'; 

    // attachment name 
    $filename = "yourinformation.pdf"; 

    // Generate headers 
    $headers = "From: $from\r\n" 
      . "MIME-Version: 1.0\r\n" 
      . "Content-Type: multipart/mixed; boundary=\"$separator\"\r\n" 
      . "X-Mailer: PHP/" . phpversion(); 

    // Generate body 
    $body = "This is a multipart message in MIME format\r\n" 
     . "--$separator\r\n" 
     . "Content-Type: text/html; charset=\"iso-8859-1\"\r\n" 
     . "\r\n" 
     . "$message\r\n" 
     . "--$separator\r\n" 
     . "Content-Type: application/pdf\r\n" 
     . "Content-Transfer-Encoding: base64\r\n" 
     . "Content-Disposition: attachment; filename=\"$filename\"\r\n" 
     . "\r\n" 
     . chunk_split(base64_encode($pdf->Output("", "S")))."\r\n" 
     . "--$separator--"; 

    // send message 
    mail($to, $subject, $body, $headers); 
+0

Ok DaveRandom, voy a intentar esto ahora mismo! ¡Gracias! –

+0

Estoy esperando que entre el correo, pero parece que la función de correo php tarda demasiado en enviar el mensaje. El primer correo electrónico siempre lleva tanto tiempo. Después del primer correo electrónico, lleva unos segundos obtener el correo electrónico. Tan pronto como reciba el primer correo electrónico, confirmaré si funciona o no. ¡Gracias! –

+1

Nada funcionó para mí, así que cambié todo, y terminé usando la clase phpmailer. ¡Gracias a todos por tu ayuda! –

Cuestiones relacionadas