Search code examples
phpemailutf-8imapdecoding

PHP imap how to decode email body correctly?


I've developed an email system on my own using php's imap and everything works fine, except for emails that are written in Arabic language, i've tried all the decoding functions and nothing seems to work. I got the subject to work perfectly by using imap_utf8 but not the email body.

This is what the email body looks like:

�
رحبا


هاي الرسالة �

This is my code:

$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
            switch ($structure->encoding) {
                case 3:
                    return imap_base64($text);
                case 4:
                    return imap_qprint($text);
                default:
                    return $text;
            }

If anyone can help with this issue. Thanks


Solution

  • I suggest you have a look at this: https://github.com/mantisbt-plugins/EmailReporting/blob/master/core/Mail/Parser.php It uses the stuff you've used as well but it adds character encoding on top of it.

    Subject character encoding can happen inline. For email bodies its one character set for the entire body

    The script given uses a pear package, not the IMAP extension but based on your input it should be pretty equal

    Hope this helps