Aviad
Aviad

Reputation: 192

How to fix "imap_utf8" doesn't work for the email's body in php imap

I created a php code to get all the new emails from gmail using imap - also in Hebrew. When I try to use the "imap_utf8" function, it's working only for the subject - and not for the body. (I also noticed that the subject has a different encoding than the body)

I searched a lot in the web, and I didn't find any solution. (I also new to php)

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

        echo imap_utf8($overview[0]->subject);
        echo imap_utf8($message);
}

I expect the output of Hebrew for the subject and the body, but only the subject works.

for example - if the subject is "נושא", and the body is "גוף", so the result is: "נושא" for the subject (And this is great), 15LXldejDQo= for the body

(And the encoded code for the subject is =?UTF-8?B?16DXldep15A=?=)

Thank's!

P.S: I'm sorry if my English is not very good.

Upvotes: 2

Views: 3282

Answers (1)

ficuscr
ficuscr

Reputation: 7054

The two functions differ slightly.

  • base64_decode — Decodes data encoded with MIME base64
  • imap_utf8 — Converts MIME-encoded text to UTF-8

If you only ever read one RFC the Multipurpose Internet Mail Extensions one is a good one to consider.

<?php
$body = '15LXldejDQo=';

var_dump(base64_decode($body)); //output: גוף
var_dump(imap_utf8($body));     //output: 15LXldejDQo=

$subject = '=?UTF-8?B?16DXldep15A=?=';
var_dump(base64_decode($subject));  //output: Q1|^�^W^�^@
var_dump(imap_utf8($subject));      //output: נושא

Basically header encoding uses a different technique. You san see this in the subject line... =?charset?encoding?encoded-text?=. The B is for base64, a Q would be fore quote-printable. The message is simply base64 encoded, the content type established by the Content-Type header.

Upvotes: 3

Related Questions