Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this mail message decode correctly?

I have this code. It's from the Zend Reading Mail example.

$message = $mail->getMessage(1);

// output first text/plain part
$foundPart = null;
foreach (new RecursiveIteratorIterator($mail->getMessage(1)) as $part) {
    try {
        if (strtok($part->contentType, ';') == 'text/plain') {
            $foundPart = $part;
            break;
        }
    } catch (Zend_Mail_Exception $e) {
        // ignore
    }
}
if (!$foundPart) {
    echo 'no plain text part found';
} else {
    echo $foundPart->getContent();
}

What I can get is the message, that works fine. But trying to decode the message into something readable does not work. I have tried Zend_Mime, imap_mime and iconv with no luck.

This is an example of what I get with $foundPart->getContent();

Hall=F3 heim=FAr

It should say "Halló heimúr"

What I would want is just some library where i could "push button, receive bacon" in practice. What I mean is, I just want to point the library to a POP3 email box and get the email in readable form (without any encoding issues) and the attachments.

imap_mime_header_decode() Gives me an array with the same data.
iconv_ mime_ decode() Does the same

Does anyone have any idea why this is happening or some library where I can just abstract this away (PHP/Python or Perl)

like image 224
Ólafur Waage Avatar asked Dec 05 '22 06:12

Ólafur Waage


1 Answers

I ran into some similar issues while learning how to use Zend_Mail for reading emails. You will need to add additional logic that Zend_Mail doesn't implement, such as decoding encoded emails, and converting the character set. Here's what I'm doing after finding the plain text part:

$content = $foundPart->getContent();

switch ($foundPart->contentTransferEncoding) {
    case 'base64':
        $content = base64_decode($content);
        break;
    case 'quoted-printable':
        $content = quoted_printable_decode($content);
        break;
}

//find the charset
preg_match('/charset="(.+)"$/', $foundPart->contentType, $matches);
$charset = $matches[1];

if ($charset == 'iso-8859-1') {
    $content = utf8_encode($content); //convert to utf8
}
like image 136
Andrew Avatar answered Dec 08 '22 15:12

Andrew