Apache commons-email是對(duì)javamailAPI的一層封裝,經(jīng)封裝后的發(fā)送郵件的代碼變得極為簡(jiǎn)單,但這里有一個(gè)中文支持的小問題。
commons-email主要的封裝類是Email類,這是一個(gè)抽象類,該框架給出了SimpleEmail的默認(rèn)實(shí)現(xiàn),但該實(shí)現(xiàn)并不支持中文,即使調(diào)用Email的setCharset也不起作用。
事實(shí)上,SimpleEmail調(diào)用了Email超類中的setContent方法來設(shè)置郵件內(nèi)容(通過setMsg方法),而在設(shè)置內(nèi)容時(shí),又采用了默認(rèn)的英文字符集,我們只要在代碼中直接調(diào)用email類的setContent方法就可以支持中文了,但要注意setContent具備兩個(gè)參數(shù),第一個(gè)是內(nèi)容對(duì)象,第二個(gè)則是內(nèi)容類型,我們把第二個(gè)參數(shù)設(shè)置為:
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);
}
}
}
}
即有一個(gè)文本解析的過程。
@2008 楊一. 版權(quán)所有. 保留所有權(quán)利