diff --git a/lib/IMAP/ImapMessageFetcher.php b/lib/IMAP/ImapMessageFetcher.php index 4d38dd2f79..ef3e7ed699 100644 --- a/lib/IMAP/ImapMessageFetcher.php +++ b/lib/IMAP/ImapMessageFetcher.php @@ -459,7 +459,6 @@ private function loadBodyData(Horde_Mime_Part $p, string $partNo, bool $isFetche } $data = $fetch->getBodyPart($partNo); - $p->setContents($data); } @@ -470,11 +469,30 @@ private function loadBodyData(Horde_Mime_Part $p, string $partNo, bool $isFetche // Only convert encoding if it is explicitly specified in the header because text/calendar // data is utf-8 by default. - $charset = $p->getContentTypeParameter('charset'); - if ($charset !== null && strtoupper($charset) !== 'UTF-8') { - $data = mb_convert_encoding($data, 'UTF-8', $charset); + $charset = mb_detect_encoding($data, 'UTF-8', true); + if (!$charset) { + $charset = $p->getCharset(); + } + + // Try the email encoding first + $converted = @mb_convert_encoding($data, 'UTF-8', $p->getCharset()); + if ($converted) { + return $converted; + } + + // Fallback + $charset = mb_detect_encoding($data, null, true); + $converted = @mb_convert_encoding($data, 'UTF-8', $charset); + if ($converted) { + return $converted; + } + + // Might be a charset that PHP mb doesn't know how to handle, fall back to iconv + $converted = iconv($charset, 'UTF-8', $data); + if ($converted === false) { + throw new ServiceException('Could not detect message charset'); } - return (string)$data; + return $converted; } private function hasAttachments(Horde_Mime_Part $part): bool {