Apache commons-email是對javamailAPI的一層封裝,經封裝后的發送郵件的代碼變得極為簡單,但這里有一個中文支持的小問題。
commons-email主要的封裝類是Email類,這是一個抽象類,該框架給出了SimpleEmail的默認實現,但該實現并不支持中文,即使調用Email的setCharset也不起作用。
事實上,SimpleEmail調用了Email超類中的setContent方法來設置郵件內容(通過setMsg方法),而在設置內容時,又采用了默認的英文字符集,我們只要在代碼中直接調用email類的setContent方法就可以支持中文了,但要注意setContent具備兩個參數,第一個是內容對象,第二個則是內容類型,我們把第二個參數設置為:
SimpleEmail.TEXT_PLAIN + "; charset=utf-8", 即可。理由如下面源代碼所示:
public void setContent(Object aObject, String aContentType)
{
......
// set the charset if the input was properly formed
String strMarker = "; charset=";
int charsetPos = aContentType.toLowerCase().indexOf(strMarker);
if (charsetPos != -1)
{
// find the next space (after the marker)
charsetPos += strMarker.length();
int intCharsetEnd =
aContentType.toLowerCase().indexOf(" ", charsetPos);
if (intCharsetEnd != -1)
{
this.charset =
aContentType.substring(charsetPos, intCharsetEnd);
}
else
{
this.charset = aContentType.substring(charsetPos);
}
}
}
}
即有一個文本解析的過程。
@2008 楊一. 版權所有. 保留所有權利