Mr. K. O. Rolling
Mr. K. O. Rolling

Reputation: 278

cryptic mail body when using imap_fetchbody

I am using following code to exctract among others the mail body of mails.

$imap = imap_open($mailbox,$user,$password);
$mails = imap_search($imap,'UNSEEN');
foreach($mails as $mail)
{
  $message = trim(utf8_encode(quoted_printable_decode(imap_fetchbody($imap,$mail,"1"))));

  if(strpos($message,"<html") !== false)
  {
    $mail_body = fopen($dir."mail.html","w");
  }
  else
  {
    $mail_body = fopen($dir."mail.txt","w");
  }
}

This is working fine and it works with every test I did. html-mails, plain-text-mails, also if the mails are forwarded.

Now from some other source I get mails, where the message (after using imap_fetchbody) just looks like some crypted string. Like this:

dGVpZW4gaW0gUERGLUZvcm1hdDoNClJla2xhbWF0aW9uc2luZm9ybWF0aW9uOiAyMTMzNjc0MSBS SV8yMTMzNjc0MS5wZGYNCg0KTWl0IGZyZXVuZGxpY2hlbiBHcsO8w59lbg0KSWhyIG5vYmlsaWEg VGVhbQ0KX19fDQoNCm5vYmlsaWEtV2Vya2UgSi4gU3RpY2tsaW5nIEdtYkggJiBDby4gS0cgfCBX YWxkc3RyLiA1My01NyB8IDMzNDE1IFZlcmwNCg0KRGllIEdlc2VsbHNjaGFmdCBpc3QgZWluZSBL

I already tried to use some other arguments for imap_fetchbody like "1.1" or "1.2", but when I do that the message is empty.

Do you have any idea why this effect occurs?

Upvotes: 1

Views: 479

Answers (1)

Mr. K. O. Rolling
Mr. K. O. Rolling

Reputation: 278

I finally found a solution. The cause seems to be forwarded mails, that were initially sent from an apple device.

Now I use this to extract the message and it works.

    $structure = imap_fetchstructure($imap, $mail);
    $part = $structure->parts[1];
    $message = imap_fetchbody($imap,$mail,1);
    if(strpos($message,"<html") !== false)
    {
      $message = trim(utf8_encode(quoted_printable_decode($message)));
    }
    else if($part->encoding == 3)
    {
      $message = imap_base64($message);
    }
    else if($part->encoding == 2)
    {
      $message = imap_binary($message);
    }
    else if($part->encoding == 1)
    {
      $message = imap_8bit($message);
    }
    else
    {
      $message = trim(utf8_encode(quoted_printable_decode(imap_qprint($message))));
    }

Upvotes: 1

Related Questions