Ver Mensaje Individual
  #1 (permalink)  
Antiguo 23/10/2009, 07:25
Avatar de neodani
neodani
 
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 18 años
Puntos: 20
Optimizar script IMAP

Buenas,

He desarrollado el siguiente script que mira el buzón de tu cuenta de correo de gmail y muestra en una tabla los siguientes campos:

Msj = Numero de mensaje
Remitente = Dirección del from
Asunto = Asunto del correo
Tamaño = Tamaño en KB o MB segun corresponda
Fecha = Fecha en formato Y-m-d H:i:s
Leido = Te dice si el correo ha sido leido (SI/NO)
ADJ = Te dice si contiene adjuntos (SI/NO)

El problema es que es muy lento y la a la que haya muchos correos da error de timeout, por defecto tenía 30, lo he subido a 60 pero no consigo solucionar mucho las cosas.

Recurro a vuestra ayuda por si veis que se pueda optimizar mi script.

Muchas gracias de antemano!

LEER_CORREO.PHP
Código php:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Chequear cuenta de correo</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <link href="imap_css.css" rel="stylesheet" type="text/css" media="all" />
  7.  
  8. </head>
  9. <body>
  10. <h1 class="titulo"> Webmail BETA </h1>
  11.  
  12. <?
  13. $imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", "user", "pass") or die("No Se Pudo Conectar Al Servidor:" . imap_last_error());
  14. $checar = imap_check($imap);
  15.  
  16. // Detalles generales de todos los mensajes del usuario.
  17. $resultados = imap_fetch_overview($imap,"1:{$checar->Nmsgs}",0);
  18. // Ordenamos los mensajes arriba los más nuevos y abajo los más antiguos
  19. krsort($resultados);
  20. $cont = 0;
  21.  
  22. // Informacion del mailbox
  23. $check = imap_mailboxmsginfo($imap);
  24.  
  25. echo "<div class='estadisticas'>";
  26. if ($check) {
  27.     echo "Fecha: "     . $check->Date    . "<br/>" ;
  28.     echo "Total Mensajes: $check->Nmsgs | Sin Leer: $check->Unread | Recientes: $check->Recent | Eliminados: $check->Deleted <br/>";
  29.     echo "Tamaño buzón: " . $check->Size . "<br/><br/>" ;
  30. } else {
  31.     echo "imap_check() failed: " . imap_last_error() . "<br />\n";
  32. }
  33. echo "</div>";
  34.  
  35.  
  36. // MOSTRAMOS EL MENSAJE
  37. echo "-------------------------------------------------------<br />";
  38. if (isset($_GET['num'])){
  39.     $num_mensaje=$_GET['num'];
  40.     echo "Mostrando cuerpo del mensaje #$num_mensaje<br/>";
  41.     $cont=0;
  42.     foreach ($resultados as $detalles) {
  43.         $cont = $cont + 1;
  44.         if ($cont == $num_mensaje){
  45.             $asunto=$detalles->subject;
  46.             echo "<p class='asunto'>$asunto</p>";}
  47.     }
  48.     $section = 1;
  49.     $mensaje = imap_fetchbody($imap, $num_mensaje, $section);
  50.     echo nl2br(strip_tags($mensaje,'<p>')); // Util para los mensajes HTML, los transforma en texto plano
  51.    
  52. }else{
  53.     echo "Mensaje no encontrado<br/>";
  54. }
  55. echo "<br />-------------------------------------------------------<br />";
  56.  
  57. ?>
  58. <table class='tabla1'>
  59. <thead>
  60.     <tr>
  61.         <th scope="col" title="Mensaje">Msj</th>
  62.         <th scope="col" title="Remitente">Remitente</th>
  63.         <th scope="col" title="Asunto">Asunto</th>
  64.         <th scope="col" title="Tamaño">Tamaño</th>
  65.         <th scope="col" title="Fecha">Fecha</th>
  66.         <th scope="col" title="Leido">Leido</th>
  67.         <th scope="col" title="Adjunto">ADJ</th>
  68.     </tr>
  69. </thead>    
  70. <?
  71.  
  72. foreach ($resultados as $detalles) {
  73.     echo "<tr>";
  74.        
  75.         // Ponemos 'Sin asunto' en caso que no tenga.
  76.         if ($detalles->subject == ''){$subject='Sin asunto';}
  77.         else{
  78.             //Evita asuntos tipo =?ISO-8859-1?Q?B=F8lla?=
  79.             $subject = utf8_decode(imap_utf8($detalles->subject));
  80.         }
  81.        
  82.         /* OBTENER EL FROM DEL MENSAJE */
  83.         $header = imap_header($imap, $detalles->msgno);
  84.         $from = $header->from;
  85.         foreach ($from as $id => $object) {
  86.             $fromname = $object->personal;
  87.             $fromaddress = $object->mailbox . "@" . $object->host;
  88.         } /* FIN DEL FROM */
  89.  
  90.        
  91.         echo "<td><b>#$detalles->msgno</b></td>";
  92.         echo "<td><b>$fromaddress</b></td>";
  93.         echo "<td><a href='leer_correo.php?num=$detalles->msgno'><b>$subject</b></a></td>";
  94.  
  95.         $tamanyo=$detalles->size;
  96.         $size=round($tamanyo/1024,2); // Pasamos a KB
  97.         if ($tamanyo<100000){
  98.             echo "<td><b> $size KB</b></td>";
  99.         }
  100.         else{
  101.             $size=round($size/1024,2); // Pasamos a MB
  102.             echo "<td><b> $size MB</b></td>";
  103.            
  104.         }
  105.         $fecha = date("Y-m-d H:i:s", strtotime($detalles->date));
  106.  
  107.         echo "<td><b>$fecha</b></td>";
  108.     if($detalles->seen == "0") {
  109.         echo "<td><b>Sin leer</b></td>";
  110.         $cont = $cont + 1;
  111.     } else {
  112.         echo "<td>Leido</td>";
  113.     }
  114.    
  115.     /* ========== TRATAR ADJUNTOS ================== */
  116.    
  117.      $mid=$detalles->msgno;
  118.      $struct = imap_fetchstructure($imap, $mid);
  119.        
  120.         $parts = $struct->parts;
  121.         $i = 0;
  122.  
  123.         if (!$parts) { /* Simple message, only 1 piece */
  124.           $attachment = array(); /* No attachments */
  125.           $content = imap_body($imap, $mid);
  126.         } else { /* Complicated message, multiple parts */
  127.        
  128.           $endwhile = false;
  129.        
  130.           $stack = array(); /* Stack while parsing message */
  131.           $content = "";    /* Content of message */
  132.           $attachment = array(); /* Attachments */
  133.        
  134.           while (!$endwhile) {
  135.             if (!$parts[$i]) {
  136.               if (count($stack) > 0) {
  137.                 $parts = $stack[count($stack)-1]["p"];
  138.                 $i     = $stack[count($stack)-1]["i"] + 1;
  139.                 array_pop($stack);
  140.               } else {
  141.                 $endwhile = true;
  142.               }
  143.             }
  144.          
  145.             if (!$endwhile) {
  146.               /* Create message part first (example '1.2.3') */
  147.               $partstring = "";
  148.               foreach ($stack as $s) {
  149.                 $partstring .= ($s["i"]+1) . ".";
  150.               }
  151.               $partstring .= ($i+1);
  152.            
  153.               if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") { /* Attachment */
  154.                 $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
  155.                                       "filedata" => imap_fetchbody($imap, $mid, $partstring));
  156.               } elseif (strtoupper($parts[$i]->subtype) == "PLAIN") { /* Message */
  157.                 $content .= imap_fetchbody($imap, $mid, $partstring);
  158.               }
  159.             }
  160.  
  161.             if ($parts[$i]->parts) {
  162.               $stack[] = array("p" => $parts, "i" => $i);
  163.               $parts = $parts[$i]->parts;
  164.               $i = 0;
  165.             } else {
  166.               $i++;
  167.             }
  168.           } /* while */
  169.         } /* complicated message */
  170.  
  171.        // echo "Analyzed message $mid, result: <br />";
  172.        // echo "Contenido: $content<br /><br />";
  173.         $num_adjuntos=count($attachment);
  174.         //echo "Numero de adjuntos: $num_adjuntos <br /><br />";
  175.        
  176.         if ($num_adjuntos>0){
  177.             echo "<td>Si</td>";
  178.             for ($i=0;$i<$num_adjuntos;$i++){
  179.                 $nombre=$attachment[$i]['filename'];
  180.                 //echo "Nombre del fichero: $nombre <br />";
  181.             }
  182.         }else{
  183.             echo "<td>No</td>";
  184.         }
  185.    
  186.     /* ========== FIN ADJUNTO ================== */
  187.  
  188.     echo "</tr>";  
  189.  
  190. }
  191. echo "</table>";
  192.  
  193. imap_close($imap);
  194.  
  195. ?>
  196. <div id="footer"> <p>Tratamiento de correo via IMAP - BETA 1.5</p></div>
  197. </body>
  198. </html>

IMAP_CSS.CSS
Código CSS:
Ver original
  1. /* Hoja de estilo */
  2.  
  3. /* ESTRUCTURA BASICA
  4. -------------------------------------------*/
  5. html,body {font-size: 1em;}
  6.  
  7. body {
  8.     color: #333;
  9.     background-color: #fff;
  10.     height:100&#37;;
  11.     width: 95%;
  12.     text-align: left;
  13.     min-width:850px;
  14.     margin: 2em auto;
  15.     padding: 0;
  16. }
  17.  
  18. #footer {
  19.     color: #666;
  20.     background:#eee;
  21.     border: 1px solid #e5e5e5;
  22.     border-width: 0 2px 2px 0;
  23.     text-align:center;
  24.     padding-top:5px;
  25.     font-family:Arial;
  26.     font-weight:bold;
  27.     margin-top:15px;
  28. }
  29.  
  30. a {text-decoration:none; color:#333;}
  31. a:hover {color:#2BBA82;}
  32.  
  33. /* ESTILO TEXTO
  34. ------------------------------------------- */
  35. .titulo{
  36.     color:#333;
  37.     font-size: 1.30em;
  38.     font-weight:normal;
  39.     text-align:justify;
  40.     line-height:20px;
  41.     padding:0px 5px 5px 20px;
  42.     margin:0.5em 0 1em;
  43. }
  44.  
  45. .asunto{
  46.     color:#60B6EF;
  47.     font-weight:bold;
  48.     font-size:1.2em;
  49. }
  50.  
  51. .estadisticas{
  52.     color:#333;
  53.     font-size: 1em;
  54.     font-weight:normal;
  55.     text-align:justify;
  56.     line-height:20px;
  57.     padding:0px 5px 5px 20px;
  58.     font-family:Arial;
  59. }
  60.  
  61. /* TABLAS ESTILO
  62. ------------------------------------------- */
  63. table,td
  64. {
  65.     border:1px solid #CCC;
  66.     border-collapse:collapse;
  67.     font:small/1.4 Verdana, "Tahoma", "Bitstream Vera Sans", Helvetica, sans-serif;
  68. }
  69. table
  70. {
  71.     border:none;
  72.     border:1px solid #CCC;
  73.     width:100%;
  74. }
  75. thead th,
  76. tbody th
  77. {
  78.  
  79.   background:#fafafb;
  80.   color:#666;  
  81.   padding:5px 10px;
  82.   border-left:1px solid #CCC;
  83.   font-weight:bold;
  84.   text-align:center;
  85.   font-size:11px;
  86.   vertical-align:middle;
  87. }
  88. tbody th
  89. {
  90.   background:#fafafb;
  91.   border-top:1px solid #CCC;
  92.   text-align:left;
  93.   font-weight:normal;
  94.  
  95. }
  96. tbody tr td
  97. {
  98.   padding:5px 10px;
  99.   color:#666;
  100.   cursor:pointer;
  101.   font-size:11px;
  102.   text-align:center;
  103.   vertical-align: middle;
  104. }
  105. tbody tr:hover {background:#F0F7FC;}
  106. tbody tr:hover td {background:#F0F7FC;}
  107.  
  108. tfoot td,
  109. tfoot th
  110. {
  111.   border-left:none;
  112.   border-top:1px solid #CCC;
  113.   padding:4px;
  114.   background:#FFF url(../imagenes/tablas/foot_bck.gif) repeat;
  115.   color:#666;
  116. }
  117. caption
  118. {
  119.     text-align:left;
  120.     font-size:100%;
  121.     padding:30px 0 10px 0px;
  122.     color:#666;
  123.     font-weight:bold;
  124.     width:500px;
  125. }
  126. table a:link {text-decoration:none; color:#60B6EF;}
  127. table a:visited {color:#333;}
  128. table a:hover {color:#2BBA82;text-decoration:none;}
  129. table a:active {color:#60B6EF;}

Última edición por neodani; 24/10/2009 a las 03:27