`
yangyi
  • 浏览: 112797 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Apache commons-Email中文问题的解决办法

    博客分类:
  • Java
阅读更多
Apache commons-email是对javamailAPI的一层封装,经封装后的发送邮件的代码变得极为简单,但这里有一个中文支持的小问题。
commons-email主要的封装类是Email类,这是一个抽象类,该框架给出了SimpleEmail的默认实现,但该实现并不支持中文,即使调用Email的setCharset也不起作用。
事 实上,SimpleEmail调用了Email超类中的setContent方法来设置邮件内容(通过setMsg方法),而在设置内容时,又采用了默认 的英文字符集,我们只要在代码中直接调用email类的setContent方法就可以支持中文了,但要注意setContent具备两个参数,第一个是 内容对象,第二个则是内容类型,我们把第二个参数设置为:
SimpleEmail.TEXT_PLAIN + "; charset=utf-8", 即可。理由如下面源代码所示:
java 代码
 
  1. public void setContent(Object aObject, String aContentType)  
  2.     {  
  3.           ......  
  4.             // set the charset if the input was properly formed  
  5.             String strMarker = "; charset=";  
  6.             int charsetPos = aContentType.toLowerCase().indexOf(strMarker);  
  7.   
  8.             if (charsetPos != -1)  
  9.             {  
  10.                 // find the next space (after the marker)  
  11.                 charsetPos += strMarker.length();  
  12.                 int intCharsetEnd =  
  13.                     aContentType.toLowerCase().indexOf(" ", charsetPos);  
  14.   
  15.                 if (intCharsetEnd != -1)  
  16.                 {  
  17.                     this.charset =  
  18.                         aContentType.substring(charsetPos, intCharsetEnd);  
  19.                 }  
  20.                 else  
  21.                 {  
  22.                     this.charset = aContentType.substring(charsetPos);  
  23.                 }  
  24.             }  
  25.         }  
  26.     }  
即有一个文本解析的过程。即有一个文本解析的过程。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics