让javamail直接添加上传文件为附件的DataSource代码
一般的javamil发送附件的代码如下:bodypart = new mimebodypart();
datasource datasource = new filedatasource("c:测试附件.doc");
bodypart.setdatahandler(new datahandler(datasource));
bodypart.setfilename(mimeutility.encodeword("测试附件.doc","gb2312", null));
multipart.addbodypart(bodypart);
由于javamail 的包里默认的对javax.activation.datasource只有两个实现:
分别是:filedatasource和urldatasource。
因此在webapp里为了不把上传的文件再保存为本地文件,然后再使用filedatasource,
我结合apache的commons fileupload组件,写了一个实现了datasource的uploadfiledatasource。
其实代码非常简单,具体代码如下:
package com.lizongbo.util;
import java.io.*;
import javax.activation.*;
import org.apache.commons.fileupload.fileitem;
/**
* <p>title: uploadfile datasource for javamail</p>
* <p>description: </p>
* <p>copyright: copyright (c) 2005</p>
* <p>company: zongboli</p>
* @author lizongbo
* @version 1.0
*/
public class uploadfiledatasource implements datasource {
private fileitem uploadfileitem = null;
public uploadfiledatasource() {
}
public uploadfiledatasource(fileitem uploadfile) {
this.uploadfileitem = uploadfile;
}
public string getcontenttype() {
return uploadfileitem.getcontenttype();
}
public inputstream getinputstream() throws ioexception {
return uploadfileitem.getinputstream();
}
public string getname() {
return uploadfileitem.getname();
}
public outputstream getoutputstream() throws ioexception {
return null;
}
public static void main(string[] args) {
}
}
附在struts里的使用例子:
if (diskfileupload.ismultipartcontent(servletrequest)) {
补充:Jsp教程,邮件