Search code examples
phpimap

Extract body text from Email PHP


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/


Solution

  • 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;