Search code examples
phpimapgmail-imap

PHP imap_fetchbody


I have been trying to fetch message but unsuccessful.

$body = imap_fetchbody($inbox, $email_id, 0);

the messages without attachments are good and I have output but with attachments gives some complicated outputs out of which both html and plain message are encoded with some (Content-Type) which is a part of gmail messages


Solution

  • You can use the following code to get the plain text part of a multipart email body:

    <?php
    
    //get the body
    $body = imap_fetchbody($inbox, $email_id, 0);
    
    //parse the boundary separator
    $matches = array();
    preg_match('#Content-Type: multipart\/[^;]+;\s*boundary="([^"]+)"#i', $body, $matches);
    list(, $boundary) = $matches;
    
    $text = '';
    if(!empty($boundary)) {
        //split the body into the boundary parts
        $emailSegments = explode('--' . $boundary, $body);
    
        //get the plain text part
        foreach($emailSegments as $segment) {
            if(stristr($segment, 'Content-Type: text/plain') !== false) {
                $text = trim(preg_replace('/Content-(Type|ID|Disposition|Transfer-Encoding):.*?\r\n/is', '', $segment));
                break;
            }
        }
    }
    
    echo $text;
    ?>