php - imap_fetchbody message is encoded

2019-04-01 18:26发布

问题:

I'm building a web app where users will be able to see emails sent to their account. I am having some issues regarding the encoding of their messages.

As a test, I just received a registration email from a website. The mail contained HTML.

It should look like this:

Thanks for signing up to Virally, we're excited to have you using our product!  
  Start Capturing Leads with Virally!  
  Click here to make your first campaign >>  
  You'll need a digital reward to create a campaign, like an eBook, Whitepaper, Video, free book chapter, Podcast etc. (We can help with this if you don't have anything of your own, just ask)  
  Please hit reply to this email if you'd like some help getting started.   
Thanks,  
 Liam Gooding  liam@virallyapp.com  Virally Co-founder    

That is how it looks in my inbox; although, on my website it looks like this:

VGhhbmtzIGZvciBzaWduaW5nIHVwIHRvIFZpcmFsbHksIHdlJ3JlIGV4Y2l0ZWQgdG8gaGF2ZSB5
b3UgdXNpbmcgb3VyIHByb2R1Y3QhwqAgCiAgU3RhcnQgQ2FwdHVyaW5nIExlYWRzIHdpdGggVmly
YWxseSEgIAogIENsaWNrIGhlcmUgdG8gbWFrZSB5b3VyIGZpcnN0IGNhbXBhaWduICZndDsmZ3Q7
ICAKICBZb3UnbGwgbmVlZCBhIGRpZ2l0YWwgcmV3YXJkIHRvIGNyZWF0ZSBhIGNhbXBhaWduLCBs
aWtlIGFuIGVCb29rLCBXaGl0ZXBhcGVyLCBWaWRlbywgZnJlZSBib29rIGNoYXB0ZXIsIFBvZGNh
c3QgZXRjLiAoV2UgY2FuIGhlbHAgd2l0aCB0aGlzIGlmIHlvdSBkb24ndCBoYXZlIGFueXRoaW5n
IG9mIHlvdXIgb3duLCBqdXN0IGFzaykgIAogIFBsZWFzZSBoaXQgcmVwbHkgdG8gdGhpcyBlbWFp
bCBpZiB5b3UnZCBsaWtlIHNvbWUgaGVscCBnZXR0aW5nIHN0YXJ0ZWQuICAgClRoYW5rcywgIAog
TGlhbSBHb29kaW5nICBsaWFtQHZpcmFsbHlhcHAuY29tICBWaXJhbGx5IENvLWZvdW5kZXIgICAg

This is my PHP code:

$openmail = imap_open($dns,$email,$password ) or die("Cannot Connect ".imap_last_error());

if ($openmail) {
  echo  "<div class='noti success'>You have ".imap_num_msg($openmail). " messages in your inbox</div>\n\r";
  $tot=imap_num_msg($openmail);
  for($i=$tot;$i>0;$i--) {

    $header = imap_header($openmail,$i);
    echo "<br>";
    echo $header->Subject." (".$header->Date.")";
    $body = imap_fetchbody($openmail, $i,'1');

    echo "<div class='faq-tile'>$body</div>";
  }
  imap_close($openmail);
}

The $body variable, is the one printing out the body of the mail.

回答1:

The content you get out of imap_fetchbody is base64 in this instance:

$body = imap_fetchbody($openmail, $i,'1');

if (preg_match('/^([a-zA-Z0-9]{76} )+[a-zA-Z0-9]{76}$/', $body)) {
    $body = base64_decode($body);
}

echo "<div class='faq-tile'>$body</div>";

You should also read Can't fetch plain text mails content using IMAP



标签: php email imap