0

Background

I am running the following code to retrieve emails using the IMAP PHP extension:

<?php
    /* connect to gmail */
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    $username = 'blah@gmail.com';
    $password = 'blah';

    $inbox = imap_open($hostname,$username,$password);

    $emails = imap_search($inbox,'ALL');

    if ($emails) {
        foreach($emails as $emailNumber) {
            $overview = imap_fetch_overview($inbox,$emailNumber,0);
            $message = imap_fetchbody($inbox,$emailNumber,"1");

            echo $overview[0]->from;
            echo $message;

        }
    }
    imap_close($inbox);
?>

Question

Having the imap_fetchbody() section argument set to 1, I am receiving the full email including headers and HTML. http://pastebin.com/np84rG7r

However, when changing the argument to 1.2 in order to identify the message as HTML, It returns nothing.

Why is this happening?

Update

I've made this little snippet of code to do the work manually until I can find out why it's not working:

$message = imap_fetchbody($inbox,$emailNumber,"1.1.1");
$doc = new DOMDocument();
$doc->loadHTML($message);
$message = trim($doc->getElementsByTagName("td")->item(0)->nodeValue);
HelpingHand
  • 1,045
  • 11
  • 26

1 Answers1

0

Unfortunately imap_fetchbody's part number depends whether your mail has html or not, and whether it has any attachment. When you have a plain text mail, then you need to use 1 instead of 1.2.

To read the complete tragedy I recommend https://www.php.net/manual/en/function.imap-fetchbody.php#89002

A cheesy way to make sure that you always get the body content is actually

$message = imap_fetchbody($inbox,$emailNumber,1.2);
if(empty($bodyText)){
    $message = imap_fetchbody($inbox,$emailNumber,1);
}
Adam
  • 25,960
  • 22
  • 158
  • 247