Search code examples
phpimap

decode mailbody correctly (imap)


I am reading mails and storing their content into a file.

It is working in general, but I have some mails with following header:

Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: base64

mb_detect_encoding($message)

returns ASCII.

When I try to read it and write the content into a file, I get cryptic text. Can you help me out? I tried any encoding I know. The output is always empty or cryptic.

My code:

$message = imap_fetchbody($imap,$mail,1);
$message = utf8_encode(imap_base64($message));

I tried following different encoding methods:

$message = utf8_encode(imap_base64($message));
//cryptic output
$message = trim(utf8_encode(quoted_printable_decode($message)));
//cryptic output
$message = imap_base64($message);
//empty output
$message = imap_binary($message);
//cryptic output
$message = imap_8bit($message);
//cryptic output
$message = utf8_encode(quoted_printable_decode(imap_base64($message)));
//empty output
$message = trim(utf8_encode(quoted_printable_decode(imap_qprint($message))));
//cryptic output

But i get nothing but cryptic output like:

hyemVleGRiMXJ6ZWRlXw0KQ29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9InV0Zi04Ig0KQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogYmFzZTY0DQoNClBHaDBiV3dnZUcxc2JuTTZka


Solution

  • I finally did it after lots of time burned.

    The problem was, that the mail header was written into the mail body as well. I dont know why, but all I had to do is delete the mail header inside the mail body (substr) before decoding it with $message = utf8_encode(imap_base64($message));