用户名: 密码: [免费注册] [忘记密码]
您的位置:首页 -- jsp技术
Javamail中文乱码问题
发布日期:2012-12-16     返回

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

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

解决办法:
在调用MimeBodyPart的setFileName()时使用Base64编码。例如:

  1. BASE64Encoder enc = new BASE64Encoder();//该类位于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. public static String getFrom(Message msg){

  2.     String from="";

  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(Exception e){

  12.       e.printStackTrace();

  13.     }

  14.     from=StringUtil.replaceStr(from,“<”,“<”);// replaceStr为字符串替换函数

  15.     from=StringUtil.replaceStr(from,">",">");

  16.     return from;

  17.   }


  18. ///////////////////StringUtil的toChinese方法//////////////////////////

  19. public static String toChinese(String strvalue){

  20.     try{

  21.       if(strvalue==null)

  22.         return null;

  23.       else{

  24.         strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");

  25.         return strvalue;

  26.       }

  27.     }catch(Exception e){

  28.       return null;

  29.     }

  30.   }



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

解决办法:
对于用base64编码过的中文,则采用base64解码,否则对附件名进行ISO8859_1到gbk的编码转换,例如:
  1. String temp=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. public static String getFromBASE64(String s) {

  10.     if (s == null) return null;

  11.     BASE64Decoder decoder = new BASE64Decoder();

  12.     try {

  13.       byte[] b = decoder.decodeBuffer(s);

  14.       return new String(b);

  15.     } catch (Exception e) {

  16.       return null;

  17.     }

  18.   }




 

典型客户
JAVA技术
 
域信息科技提供专业的jsp空间服务,jsp空间,jsp空间租用,jsp空间购买,虚拟JSP主机,jsp主机,独享TOMCAT,JSP服务器
售前电话:400-004-4994
售后电话:400-004-4994
技术支持(7×24支持):400-004-4994 018241839456
公司地址:阜新市中华路65号新天地大厦9F
邮编:123000       传真:0418-2493388-606
经营性ICP证:辽B-2-4-20070114    ICP备案: 辽ICP备07005704号
域信息科技提供专业的jsp空间,虚拟JSP主机,jsp主机,独享TOMCAT,JSP服务器
域信息科技提供专业的jsp空间,虚拟JSP主机,jsp主机,独享TOMCAT,JSP服务器