Apache commons-email是对javamailAPI的一层封装,经封装后的发送邮件的代码变得极为简单,但这里有一个中文支持的小问题。
commons-email主要的封装类是Email类,这是一个抽象类,该框架给出了SimpleEmail的默认实现,但该实现并不支持中文,即使调用Email的setCharset也不起作用。
事 实上,SimpleEmail调用了Email超类中的setContent方法来设置邮件内容(通过setMsg方法),而在设置内容时,又采用了默认 的英文字符集,我们只要在代码中直接调用email类的setContent方法就可以支持中文了,但要注意setContent具备两个参数,第一个是 内容对象,第二个则是内容类型,我们把第二个参数设置为:
SimpleEmail.TEXT_PLAIN + "; charset=utf-8", 即可。理由如下面源代码所示:
java 代码
- 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);
- }
- }
- }
- }
即有一个文本解析的过程。