Javamail中的常见中文乱码问题与解决办法(综合)

在使用javamailapi开发邮件服务系统时,我们常常会碰到很多中文乱码问题,下面就分别介绍如何解决这些问题。

1.发送名称含中文的附件到邮件服务器,用别的邮件接收程序接收到的附件名显示为乱码

解决办法:
在调用MimeBodyPart的setFileName()时使用Base64编码。例如:
  1. BASE64Encoderenc=newBASE64Encoder();//该类位于jre/lib/rt.jar中
  2. //fds为FileDataSource实例
  3. mbp.setFileName("=?GBK?B?"+enc.encode((fds.getName()).getBytes())+"?=");


2.接收邮件时,获取某些邮件发送程序发送的email地址,发送地址显示为乱码

解决办法:
对含有中文的发送地址,使用MimeUtility.decodeTex方法,对其他则把地址从ISO8859_1编码转换成gbk编码,见下例
  1. publicstaticStringgetFrom(Messagemsg){
  2. Stringfrom="";
  3. try{
  4. if(msg.getFrom()[0]!=null)
  5. from=msg.getFrom()[0].toString();
  6. if(from.startsWith("=?GB")||from.startWith(“=?gb”)){
  7. from=MimeUtility.decodeText(from);
  8. }else{
  9. from=StringUtil.toChinese(from);
  10. }
  11. }catch(Exceptione){
  12. e.printStackTrace();
  13. }
  14. from=StringUtil.replaceStr(from,“<”,“<”);//replaceStr为字符串替换函数
  15. from=StringUtil.replaceStr(from,">",">");
  16. returnfrom;
  17. }
  18. ///////////////////StringUtil的toChinese方法//////////////////////////
  19. publicstaticStringtoChinese(Stringstrvalue){
  20. try{
  21. if(strvalue==null)
  22. returnnull;
  23. else{
  24. strvalue=newString(strvalue.getBytes("ISO8859_1"),"GBK");
  25. returnstrvalue;
  26. }
  27. }catch(Exceptione){
  28. returnnull;
  29. }
  30. }


3.接收邮件时,获取某个邮件的中文附件名,出现乱码

解决办法:
对于用base64编码过的中文,则采用base64解码,否则对附件名进行ISO8859_1到gbk的编码转换,例如:
  1. Stringtemp=part.getFileName();//part为Part实例
  2. if((temp.startsWith("=?GBK?B?")&&temp.endsWith("?="))
  3. ||(temp.startsWith("=?gbk?b?")&&temp.endsWith("?="))){
  4. temp=StringUtil.getFromBASE64(temp.substring(8,temp.indexOf("?=")-1));
  5. }else{
  6. temp=StringUtil.toChinese(temp);//该方法如前所叙
  7. }
  8. /////////////StringUtil的getFromBASE64方法/////////
  9. publicstaticStringgetFromBASE64(Strings){
  10. if(s==null)returnnull;
  11. BASE64Decoderdecoder=newBASE64Decoder();
  12. try{
  13. byte[]b=decoder.decodeBuffer(s);
  14. returnnewString(b);
  15. }catch(Exceptione){
  16. returnnull;
  17. }
  18. }



乱码问题的调试步骤总结:

基本上在javamail中碰到的中文乱码问题就这么多了,如果你的程序出现了中文乱码,首先不要惊慌,可用多个其他的邮件发送或接收程序进行验证,看是在哪个环节出现了问题,然后再仔细对照原文和乱码,调用相应的编码解码方法就行了。



最后,希望这篇短文能对你有所启发,祝你成功。

你可能感兴趣的:(javamail)