ccc

API Gmail: Obtener los correos de gmail con PHP

a) En tu php.ini tiene que estar habilitado extension=php_imap.dll

b) En la configuración de tu cuenta de gmail ir a Settings -> Forwarding and POP/IMAP and enable IMAP access.

Una forma más rápida de hacer es directamente dar al siguiente enlace y habilitarlo: https://www.google.com/settings/security/lesssecureapps

El código sería:
if (! function_exists('imap_open')) {
echo "IMAP is not configured.";
exit();
}
$usercuenta = "pepitoperez@gmail.com";
$pwCuenta = "123456";
$connection = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', $usercuenta, $pwCuenta) or die('Cannot connect to Gmail: ' . imap_last_error());
$emailData = imap_search($connection, 'SUBJECT "Come bien"');
if (! empty($emailData)) { ?>
<table border=1>
<?php
foreach ($emailData as $emailIdent) {
$overview = imap_fetch_overview($connection, $emailIdent, 0);
$message = imap_fetchbody($connection, $emailIdent, '1.1');
$messageExcerpt = substr($message, 0, 350);
$partialMessage = trim(quoted_printable_decode($messageExcerpt));
$date = date("d F, Y", strtotime($overview[0]->date));
?>
<tr>
<td><?=$overview[0]->from;?></td>
<td><?=$overview[0]->subject; ?></td>
<td><?=$partialMessage; ?></td>
<td><?=$date; ?></td>
</tr>
<?php
} // End foreach
?>
</table>
<?php
} // end if
imap_close($connection);

Más información en: https://phppot.com/php/gmail-email-inbox-using-php-with-imap/

Si queremos que muestre el valor de los documentos adjuntos que tengan los emails habría que:
...
foreach ($emailData as $emailIdent) {
   $structure = imap_fetchstructure($connection, $emailIdent);
   require("getAdjuntos.php");
   $overview = imap_fetch_overview($connection, $emailIdent, 0);
...

getAdjuntos.php:
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {

$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);

if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}

if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}

if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $emailIdent, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}

// si el fichero adjunto se trata de un zip hay q descomprimirlo
foreach($attachments as $attachment) {
    if($attachment['is_attachment'] == 1) {
        $filename = $attachment['name'];
if (strpos($filename, ".zip") !== FALSE) {
            $fp = fopen('temp_zip/'.$filename, "w+"); // la carpeta temp_zip tiene q estar ya creada
            fwrite($fp, $attachment['attachment']);
            fclose($fp);

            /* Uncompress zip file */
// echo "<br>FILENAME:".$attachment['filename']."<br>";
$zip = new ZipArchive;
            if ($zip->open("temp_zip/".$attachment['filename']) === TRUE) {
$zip->extractTo('temp_zip');
$zip->close();
echo "descomprimido<hr>";
/* Deleting temp files */
// array_map('unlink', glob("temp_zip/*.*"));
            }
            else {
                    echo "ERROR AL DESCOMPRIMIR";
                    die;
            }
        }
    }
}


Más información en: https://www.electrictoolbox.com/extract-attachments-email-php-imap/

No hay comentarios:

Publicar un comentario