PHP Imap Decoding Messages

PHP IMAP decoding messages

imap_bodystruct() or imap_fetchstructure() should return this info to you. The following code should do exactly what you're looking for:

<?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());

$emails = imap_search($inbox,'ALL');

if($emails) {
$output = '';
rsort($emails);

foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$structure = imap_fetchstructure($inbox, $email_number);

if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($inbox,$email_number,2);

if($part->encoding == 3) {
$message = imap_base64($message);
} else if($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_qprint($message);
}
}

$output.= '<div class="toggle'.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="from">From: '.utf8_decode(imap_utf8($overview[0]->from)).'</span>';
$output.= '<span class="date">on '.utf8_decode(imap_utf8($overview[0]->date)).'</span>';
$output.= '<br /><span class="subject">Subject('.$part->encoding.'): '.utf8_decode(imap_utf8($overview[0]->subject)).'</span> ';
$output.= '</div>';

$output.= '<div class="body">'.$message.'</div><hr />';
}

echo $output;
}

imap_close($inbox);
?>

decode mailbody correctly (imap)

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));

PHP imap how to decode email body correctly?

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

PHP IMAP Decode UTF-8 email body

Problem solved :
I used :

iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $data)

instead of :

iconv("UTF-8", "Windows-1252", $data)

And it works great now.



Related Topics



Leave a reply



Submit