欢迎光临
我们一直在努力

让javamail直接添加上传文件为附件的DataSource代码-JSP教程,邮件相关

建站超值云服务器,限时71元/月

一般的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直接运行, 给我带来了很大的麻烦(发了很多垃圾邮件到我邮箱 🙁 ),

从现在开始发布的代码,一律转为小写之后再进行发布,以仅供阅读参考。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 让javamail直接添加上传文件为附件的DataSource代码-JSP教程,邮件相关
分享到: 更多 (0)

相关推荐

  • 暂无文章