2010-11-24 48 views
5

Actualmente estoy usando una transmisión imap para recibir correos electrónicos de una bandeja de entrada.Extraer texto del cuerpo del correo electrónico PHP

Todo funciona bien excepto que no estoy seguro de cómo obtener el texto del cuerpo y el título del correo electrónico. Si hago imap_body ($ connection, $ message), el equivalente base 64 del archivo adjunto al correo electrónico se incluye en el texto.

Actualmente estoy usando esta función para obtener los archivos adjuntos.

http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/

Gracias

Respuesta

19

funcionar bien php de IMAP no son divertido trabajar con él. Un usuario en esta página explica las incoherencias con la obtención de correos electrónicos: http://php.net/manual/en/function.imap-fetchbody.php#89002

Usando su información útil, creé de manera confiable el texto del cuerpo de un correo electrónico.

$bodyText = imap_fetchbody($connection,$emailnumber,1.2); 
if(!strlen($bodyText)>0){ 
    $bodyText = imap_fetchbody($connection,$emailnumber,1); 
} 
$subject = imap_headerinfo($connection,$i); 
$subject = $subject->subject; 

echo $subject."\n".$bodyText; 
+0

muchas gracias. Después de buscar en Google durante 4 horas, encontré el ejemplo de trabajo. –

+1

¿De qué se trata el '1.2'? – pguardiario

+0

@pguardiario No tengo ni idea, aunque si hace clic en el enlace de arriba podría ayudar a algunos. Creo que llegué a la solución con prueba y error. – William

0

También puede probar estos

content-type:text/html 

$message = imap_fetchbody($inbox,$email_number, 2); 

content-type:plaintext/text 

$message = imap_fetchbody($inbox,$email_number, 1); 
1

Mi solución (funciona con todos los tipos y juego de caracteres):

function format_html($str) { 
    // Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf 
    $str = htmlentities($str, ENT_COMPAT, "UTF-8"); 
    $str = str_replace(chr(10), "<br>", $str); 
    return $str; 
} 


// Start 

$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno); 

// Recherche de la section contenant le corps du message et extraction du contenu 
$obj_section = $obj_structure; 
$section = "1"; 
for ($i = 0 ; $i < 10 ; $i++) { 
    if ($obj_section->type == 0) { 
     break; 
    } else { 
     $obj_section = $obj_section->parts[0]; 
     $section.= ($i > 0 ? ".1" : ""); 
    } 
} 
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section); 
// Décodage éventuel 
if ($obj_section->encoding == 3) { 
    $text = imap_base64($text); 
} else if ($obj_section->encoding == 4) { 
    $text = imap_qprint($text); 
} 
// Encodage éventuel 
foreach ($obj_section->parameters as $obj_param) { 
    if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) { 
     $text = utf8_encode($text); 
     break; 
    } 
} 

// End 
print format_html($text); 
Cuestiones relacionadas