Email中附件名称中包含中文字符显示乱码

Email中附件名称中包含中文字符显示乱码是因为附件虽包含了中文字,但没有指定对应的编码,导致Android按默认编码UTF-8去显示中文字而显示了乱码

邮件中的附件名称包含中文字并指定了encode
Content-Type: audio/mpeg; name="=?gb2312?B?us+zyS5tcDM=?="
Content-Description: =?gb2312?B?us+zyS5tcDM=?=
Content-Disposition: attachment; filename="=?gb2312?B?us+zyS5tcDM=?=";
size=6313900; creation-date="Wed, 13 Sep 2017 10:01:46 GMT";
modification-date="Tue, 28 Nov 2017 08:41:13 GMT"
Content-Transfer-Encoding: base64


邮件中的附件名称包含中文字未指定encode
----_com.android.email_1076710617800
Content-Type: image/png;
name="朱.png"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="朱.png";
size=58864

修正
android\packages\apps\Email\provider_src\com\android\email\LegacyConversions.java
 @VisibleForTesting
    protected static Attachment mimePartToAttachment(final Part part) throws MessagingException {
        // Transfer fields from mime format to provider format
        String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
        String ramContentType = part.getContentType();
        if (ramContentType.indexOf("=?") == -1) {
            LogUtils.v(LogUtils.TAG, "original contentType donnot contain charset and encode");
            String unfoldContentType = MimeUtility.unfold(ramContentType);
            try {
                String charset = getEncoding(unfoldContentType);
                LogUtils.v(LogUtils.TAG, "translate the contentType with: " + charset);
                contentType = new String(unfoldContentType.getBytes(charset), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                LogUtils.v(LogUtils.TAG, "translate the contentType happen UnsupportedEncodingException: ");
                contentType = MimeUtility.unfoldAndDecode(part.getContentType());
            }
        } else {
            contentType = MimeUtility.unfoldAndDecode(part.getContentType());
        }
......


  private static String getEncoding(String str) {
        String encode[] = new String[]{
                "ISO-8859-1",
                "GB2312",
                "GBK",
                "GB18030",
                "Big5",
                "Unicode",
                "ASCII",
                "UTF-8"
        };
        for (int i = 0; i < encode.length; i++) {
            try {
                if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
                    return encode[i];
                }
            } catch (Exception ex) {
                LogUtils.v(LogUtils.TAG, "getEncoding: " + ex.toString());
            }
        }

        return "UTF-8";
    }

猜你喜欢

转载自aijiawang-126-com.iteye.com/blog/2401160
今日推荐