Javamail中的常见中文乱码问题与解决办法
在使用javamail?api开发邮件服务系统时,我们常常会碰到很多中文乱码问题,下面就分别介绍如何解决这些问题。
1.发送名称含中文的附件到邮件服务器,用别的邮件接收程序接收到的附件名显示为乱码
解决办法:
在调用MimeBodyPart的setFileName()时使用Base64编码。例如:
String temp=part.getFileName();//part为Part实例 if((temp.startsWith("=?GBK?B?")&&temp.endsWith("?=")) ||(temp.startsWith("=?gbk?b?")&&temp.endsWith("?="))){ temp=StringUtil.getFromBASE64(temp.substring(8,temp.indexOf("?=")-1)); }else{ temp=StringUtil.toChinese(temp);//该方法如前所叙 } /////////////StringUtil的getFromBASE64方法///////// public static String getFromBASE64(String s) { if (s == null) return null; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(s); return new String(b); } catch (Exception e) { return null; } } ?
乱码问题的调试步骤总结:
基本上在javamail中碰到的中文乱码问题就这么多了,如果你的程序出现了中文乱码,首先不要惊慌,可用多个其他的邮件发送或接收程序进行验证,看是在哪个环节出现了问题,然后再仔细对照原文和乱码,调用相应的编码解码方法就行了。