讓javamail直接添加上傳文件為附件的DataSource代碼

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- 讓javamail直接添加上傳文件為附件的DataSource代碼 (http://www.webasp.net/article/17/16975.htm)
-- 作者:未知
-- 發佈日期: 2005-03-14
一般的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直接運行, 給我帶來了很大的麻煩(發了很多垃圾郵件到我郵箱 :( ),
從現在開始發佈的代碼,一律轉為小寫之後再進行發佈,以僅供閱讀參考。





webasp.net