Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract body text from Email PHP

Tags:

php

imap

I am currently using an imap stream to get emails from an inbox.

Everything is working fine except I am unsure how to get the body text and title of the email. If I do imap_body($connection,$message) the base 64 equivalent of the email attachment is included in the text.

I am currently using this function to get the attachments.

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

like image 232
Lime Avatar asked Nov 24 '10 23:11

Lime


2 Answers

Well php imap's function are not fun to work with. A user on this page explains the inconsistencies with getting emails: http://php.net/manual/en/function.imap-fetchbody.php#89002

Using his helpful information I created a reliably way to get an email's body text.

$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;
like image 188
Lime Avatar answered Oct 13 '22 19:10

Lime


My solution (works with all types and charset) :

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);
like image 23
Jerry Avatar answered Oct 13 '22 21:10

Jerry