一般的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)) {
diskfileupload fileupload = new diskfileupload();
fileupload.setsizemax(1024 * 1024);
try {
list filelist = fileupload.parserequest(servletrequest);
iterator itr = filelist.iterator();
fileitem item;
while (itr.hasnext()) {
item = (fileitem) itr.next();
if (item.isformfield()) {
logger.debug(item.getfieldname() + "=" +
item.getstring() + "");
} else {
mimebodypart bodypart = new mimebodypart();
datasource datasource = new com.webmail.util.uploadfiledatasource(item);
bodypart.setdatahandler(new datahandler(datasource));
multipart.addbodypart(bodypart); }
}
} catch (org.apache.commons.fileupload.fileuploadbase.
sizelimitexceededexception sle) {
logger.debug("size is too large", sle);
} catch (org.apache.commons.fileupload.fileuploadbase.
unknownsizeexception use) {
logger.debug("unknown size ", use);
} catch (org.apache.commons.fileupload.fileuploadexception fue) {
logger.debug(fue.getmessage() + " ");
} catch (exception e) {
logger.debug("chucuo", e);
}
} else {
logger.debug("没有附件!!!");
}
由于《用javamail免认证方式发送邮件给163.com的用户的完整代码实例。》 代码被人copy直接运行, 给我带来了很大的麻烦(发了很多垃圾邮件到我邮箱 :( ),
从现在开始发布的代码,一律转为小写之后再进行发布,以仅供阅读参考。