Foros del Web » Programando para Internet » PHP »

Optimizar script IMAP

Estas en el tema de Optimizar script IMAP en el foro de PHP en Foros del Web. 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: ...
  #1 (permalink)  
Antiguo 23/10/2009, 07:25
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 1 mes
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
  #2 (permalink)  
Antiguo 23/10/2009, 08:53
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Optimizar script IMAP

Sí son muchos correos mejor solo extrae una parte de los correos e implementa un paginador para poderte mover entre paginas de correos.

Saludos.
  #3 (permalink)  
Antiguo 24/10/2009, 03:32
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 1 mes
Puntos: 20
Respuesta: Optimizar script IMAP

Cita:
Iniciado por GatorV Ver Mensaje
Sí son muchos correos mejor solo extrae una parte de los correos e implementa un paginador para poderte mover entre paginas de correos.

Saludos.
He comentado las lineas en las que recuperaba el body del mensaje, ya que para generar la vista previa de la tabla no lo veía necesario.

También he añadido un pequeño script para saber cuanto tarda en cargar la página y sigue siendo muy muy lento! y eso que solo muestra 15 mensajes! no 50 ni 100

La página fue creada en 26.1034967899 segundos



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

En cambio en otro script que tengo donde no trato si tiene adjuntos o no, me carga 168 mensajes! en el mismo tiempo

La página fue creada en 25.0225231647 segundos

Parece que es la función de saber si tiene adjunto o no la que está dando problemas!!

¿Alguna idea de por qué me hace ir tan lento?


Código php:
Ver original
  1. <?$mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $tiempoinicial = $mtime; ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <title>Chequear cuenta de correo</title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7. <link href="imap_css.css" rel="stylesheet" type="text/css" media="all" />
  8.  
  9. </head>
  10. <body>
  11. <h1 class="titulo"> Webmail BETA </h1>
  12.  
  13. <?
  14. $imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", "user", "pass") or die("No Se Pudo Conectar Al Servidor:" . imap_last_error());
  15. $checar = imap_check($imap);
  16.  
  17. // Detalles generales de todos los mensajes del usuario.
  18. $resultados = imap_fetch_overview($imap,"1:{$checar->Nmsgs}",0);
  19. // Ordenamos los mensajes de más nuevos a más antiguos
  20. krsort($resultados);
  21. $cont = 0;
  22.  
  23. // Informacion del mailbox
  24. $check = imap_mailboxmsginfo($imap);
  25.  
  26. echo "<div class='estadisticas'>";
  27. if ($check) {
  28.     echo "Fecha: "     . $check->Date    . "<br/>" ;
  29.     //echo "Driver: "   . $check->Driver  . "<br />\n" ;
  30.     //echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
  31.     echo "Total Mensajes: $check->Nmsgs | Sin Leer: $check->Unread | Recientes: $check->Recent | Eliminados: $check->Deleted <br/>";
  32.     echo "Tamaño buzón: " . $check->Size . "<br/><br/>" ;
  33. } else {
  34.     echo "imap_check() failed: " . imap_last_error() . "<br />\n";
  35. }
  36. echo "</div>";
  37.  
  38. // MOSTRAMOS EL MENSAJE
  39. echo "-------------------------------------------------------<br />";
  40. if (isset($_GET['num'])){
  41.     $num_mensaje=$_GET['num'];
  42.     echo "Mostrando cuerpo del mensaje #$num_mensaje<br/>";
  43.     $cont=0;
  44.     foreach ($resultados as $detalles) {
  45.         $cont = $cont + 1;
  46.         if ($cont == $num_mensaje){
  47.             $asunto=$detalles->subject;
  48.             echo "<p class='asunto'>$asunto</p>";}
  49.     }
  50.  
  51.     $section = 1;
  52.     $mensaje = imap_fetchbody($imap, $num_mensaje, $section);
  53.     echo nl2br(strip_tags($mensaje,'<p>')); // Util para los mensajes HTML, los transforma en texto plano
  54.    
  55. }else{
  56.     echo "Mensaje no encontrado<br/>";
  57. }
  58. echo "<br />-------------------------------------------------------<br />";
  59.  
  60. ?>
  61. <table class='tabla1'>
  62. <thead>
  63.     <tr>
  64.         <th scope="col" title="Mensaje">Msj</th>
  65.         <th scope="col" title="Remitente">Remitente</th>
  66.         <th scope="col" title="Asunto">Asunto</th>
  67.         <th scope="col" title="Tamaño">Tamaño</th>
  68.         <th scope="col" title="Fecha">Fecha</th>
  69.         <th scope="col" title="Leido">Leido</th>
  70.     </tr>
  71. </thead>   
  72. <?
  73. //$i=0;
  74. foreach ($resultados as $detalles) {
  75.     echo "<tr>";
  76.     //echo "Para: $detalles->to <br>";
  77.    
  78.     // Ponemos 'Sin asunto' en caso que no tenga.
  79.     if ($detalles->subject == ''){$subject='Sin asunto';}
  80.     else{
  81.         //Evita asuntos tipo =?ISO-8859-1?Q?B=F8lla?=
  82.         $subject = utf8_decode(imap_utf8($detalles->subject));
  83.     }
  84.     $from = utf8_decode(imap_utf8($detalles->from));
  85.    
  86.     // Mirar si tiene adjuntos
  87.     $msg_structure = imap_fetchstructure($imap, $detalles->msgno);
  88.    
  89.        
  90.        
  91.     echo "<td><b>#$detalles->msgno</b></td>";
  92.     echo "<td><b>$from</b></td>";
  93.     echo "<td><a href='correo_imap.php?num=$detalles->msgno'><b>$subject</b></a></td>";
  94.     //echo "<td><a href='mostrar_correo.php?msj=$detalles->msgno'><b>$subject</b></a></td>";
  95.     echo "<td><b>$detalles->size bytes</b></td>";
  96.     echo "<td><b>$detalles->date</b></td>";
  97.    
  98.    
  99.        
  100.     if($detalles->seen == "0") {
  101.         echo "<td><b>Sin leer</b></td>";
  102.         $cont = $cont + 1;
  103.     } else {
  104.         echo "<td>Leido</td>";
  105.     }
  106.    
  107.        
  108.     //$servidorenvia = strstr($detalles->message_id, '@');
  109.     //echo "Dominio Que Envia: $servidorenvia<br><hr>";
  110.     echo "</tr>";
  111.    
  112. //  $i=$i+1;
  113. //  $mi_array=array($i=>$detalles->msgno,$from,$subject,$detalles->size,$detalles->date);
  114.  
  115.    
  116.  
  117. }
  118. echo "</table>";
  119.  
  120. //foreach ($mi_array as $indice=>$actual)
  121. //    echo $actual . "<br>";
  122.    
  123.  
  124. imap_close($imap);
  125. $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $tiempofinal = $mtime; $tiempototal = ($tiempofinal - $tiempoinicial); echo "La página fue creada en ".$tiempototal." segundos";
  126. ?>
  127. <div id="footer"> <p>Tratamiento de correo via IMAP - BETA 1.0</p></div>
  128. </body>
  129. </html>

Última edición por neodani; 24/10/2009 a las 03:48
  #5 (permalink)  
Antiguo 26/10/2009, 10:16
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Optimizar script IMAP

Lo que pasa es que al usar fetchstructure bajas todo el correo completo, por eso es mejor usar fetch_overview para ver si tiene o no attachments y luego procesarlo por aparte.

Saludos.
  #6 (permalink)  
Antiguo 27/10/2009, 01:04
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 1 mes
Puntos: 20
Respuesta: Optimizar script IMAP

Cita:
Iniciado por GatorV Ver Mensaje
Lo que pasa es que al usar fetchstructure bajas todo el correo completo, por eso es mejor usar fetch_overview para ver si tiene o no attachments y luego procesarlo por aparte.

Saludos.
El problema GatorV es que la función fetch_overview no te muestra si tiene adjuntos o no.

Te pongo una muestra del array que te imprime.

Código:
Array
(
    [13] => stdClass Object
        (
            [subject] => prueba
            [from] => [email protected]
            [to] => [email protected]
            [date] => Sat, 24 Oct 2009 07:32:21 -0700
            [message_id] => <[email protected]>
            [size] => 2456
            [uid] => 3100
            [msgno] => 14
            [recent] => 0
            [flagged] => 0
            [answered] => 0
            [deleted] => 0
            [seen] => 1
            [draft] => 0
        )
Por lo que no sirve fetch_overview para sacar los adjuntos.

¿No queda otra que bajar el contenido?

Gracias de antemano
  #7 (permalink)  
Antiguo 27/10/2009, 08:32
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Optimizar script IMAP

Otra opción es que uses una base de datos local y solo escanees los mensajes nuevos así no dependes al 100% de tu script en el webmail.

Saludos.
  #8 (permalink)  
Antiguo 27/10/2009, 18:53
 
Fecha de Ingreso: abril-2006
Mensajes: 1.128
Antigüedad: 18 años
Puntos: 33
Respuesta: Optimizar script IMAP

neodani:
Neodani:
Primeramente, antes de imap_check debes implementar algo que te informa
si HAY o NO hay correos; ya que si NO hay y corres la funcion que sigue
salen errores en los logs del Apache.
Eso se hace con->
$cantidadcorr = imap_num_msg($imap);
if($cantidadcorr < "1") {
echo "No hay correo en.......";
Aqui haces un exit();
}
Segundo para saber si hay attachments,
lo mas sencillo es esto ->
$mensajeadjunto = imap_fetchstructure($imap, $analisarcorreo);
$partes = count($mensajeadjunto->parts);
$partesreales = $partes-1;
if(!$partes) {
echo "<b>ARCHIVOS ADJUNTOS = 0<br>";
imap_close($imap);
exit();
}
El codigo no debiera estar lento como tu dices.
Pero si el problema continua, separalo en dos codigos
y que el usuario pase del primero al segundo si asi
lo desea.
Saludos
Franco
  #9 (permalink)  
Antiguo 01/11/2009, 18:58
 
Fecha de Ingreso: noviembre-2009
Mensajes: 1
Antigüedad: 14 años, 6 meses
Puntos: 0
De acuerdo Respuesta: Optimizar script IMAP

oye hermano, mira yo te encomendara que no bajes los adjuntos al momento de cargar el script de la pagina pues generar demasiada información, y dependiendo los adjuntos que tengas puedes bajar incluso mas de 20mb una sola paginita,
por lo tanto, optimiza ese script, de una manera en la que solo te muestre los datos osea, solo sabras el nombre del adjunto, e imprimiras, si gustas imprimelo como link, o boton, no metas codigo dentro como el de imap_fetchbody($inbox,$email_number,2 o <1>) por que este te enviaa todooss los datos del body TODOS, con todo y adjuntos, entonses solo utiliza para adquirir la informacion el imap_fetchstructure($inbox, $email_number) para informacion y el fetchbody para el mensaje el 1.1(plain) y el 1.2(html), entonses gracias ala imprecion de botones o links, puedes poner en if(isset(botonpresionado o link)) y dentro de esa condicion entonses si metes el fetchbody para que solo en el caso que quieras el adjunto lo baje, no que lo baje aunque no lo quieras como es tu caso, la variable del boton pues la puedes enviar con post en un form, o recibir la variable mediante get en la url, o puedes mandar llamar a otro script que tenga las lineas de codigo que necesiten para la descarga solo de un attachment, obviamente mandando la variable del boton presionado, y del numero de mensaje que quieres el attachment, y es todo, la pagina te muestra que tiene attachs, y hasta cuantos pero no los descarga amenos que tu le des click al boton descargar o al link, buenooo

asi lo tengo io espero te de ideas, mi problema hoy en dia ess, que hacer si hay mas de 1 attach en un mensaje, ahi por si alguien sabe de una vez, me diga por favor, se traerme la informacion gracias al numero de partes, si es mas de 1son attach, peroo la estructura nomas, paraa traermee la informacion del 2do attachment o incluso un tercero, es lo que no logro dar,
con el imap_fetchbody($inbox, $numero_email, 2) el 2 te trae solo el attach, pero nomas el primero, aunque haya 2, bueno espero servir de ayuda, y que me ayuden de pasada, saludos, siento tanta letra.

Última edición por DarKKer666; 01/11/2009 a las 19:03
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 05:52.