Search code examples
phpgmailimap

Locate HTML and plain text using imap_fetchstructure


I want to locate the html and/or the plain text using the imap_fetchstructure. I tried several solutions but the emails don't have always the same structure. I'm actually using:

$message=imap_fetchbody($inbox, $number, "1.2.1");
if ($message== "") { 
  $message =imap_fetchbody($inbox, $number, "1.1"); 
}
if ($message== "") {
    $message = imap_fetchbody($inbox, $number, "1"); 
} 
    $message = imap_qprint($body);

When trying this; the result is sometimes correct and sometimes returning The content of the attachements depending on the mail server. So I want a solution based on Imap_fetchstructure.


Solution

  • I found an answer for my question:

    function getBody($uid, $imap) {
        $body = $this->get_part($imap, $uid, "TEXT/HTML");
        // if HTML body is empty, try getting text body
        if ($body == "") {
            $body = $this->get_part($imap, $uid, "TEXT/PLAIN");
        }
        return $body;
    }
    
    function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
        if (!$structure) {
           $structure = imap_fetchstructure($imap, $uid, FT_UID);
        }
        if ($structure) {
            if ($mimetype == $this->get_mime_type($structure)) {
                if (!$partNumber) {
                    $partNumber = 1;
                }
                $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
                switch ($structure->encoding) {
                    case 3: return imap_base64($text);
                    case 4: return imap_qprint($text);
                    default: return $text;
                }
            }
    
            // multipart
            if ($structure->type == 1) {
                foreach ($structure->parts as $index => $subStruct) {
                    $prefix = "";
                    if ($partNumber) {
                        $prefix = $partNumber . ".";
                    }
                    $data = $this->get_part($imap, $uid, $mimetype, $subStruct,
                        $prefix. ($index + 1));
                    if ($data) {
                        return $data;
                    }
                }
            }
        }
        return false;
    }
    
    function get_mime_type($structure) {
        $primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION",
            "AUDIO", "IMAGE", "VIDEO", "OTHER");
    
        if ($structure->subtype) {
           return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
        }
        return "TEXT/PLAIN";
    }