Me mandan unos correos y me conecto por imap y obtengo la información de los correos, el problema es como descargar los ficheros adjuntos.
Haciendo un imap_fetchbody entiendo que tengo ahí todas las propiedades. Me duelve un array y uno de los campos es:
Content-Type: X-MS-Has-Attach:
que supongo que es lo que me indica si hay adjuntos. Pero como los descargo?
Bueno ya lo he conseguido entre cosas mías y copiadas de por ahí, pongo el código de mi función "buscar" (solo quiero los emails que tengan cierto adjunto)
por si le sirve a alguien. Fácil de adaptar.
Código PHP:
Ver originalpublic function buscar($asunto, $ficheroBusqueda) {
if ($emails) {
/* Poner los emails más nuevos arriba */
foreach ( $emails as $email ) {
if (strpos ( $propiedades [0]->subject, $asunto )) {
// ompruebo si hay ficheros adjuntos
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 ( $this->conexion, $email, $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
}
}
}
}
foreach ( $attachments as $adjunto ) {
if ($adjunto ['is_attachment']) {
$nombreFichero = $adjunto ['filename'];
$adjunto = $adjunto ['attachment'];
echo "Comparando $ficheroBusqueda con $nombreFichero<br />";
if ($ficheroBusqueda == $nombreFichero) {
if ($adjunto) {
$gestor = fopen ( $nombreFichero, 'w' ); return $nombreFichero;
}
} // Fin de nombre fichero
} // Fin de es adjunto
} // Fin de foreach adjunto
} // Fin de si coincide el asunto
} // Fin de foreach email
} // Fin de si hay emails
return false; // Sólo sino encontró ficheros
} // Fin de buscar correos