一般的javamil发送附件的代码如下:
BodyPart bodypart=new MimeBodyPart();
String FileName="d://测试文件.doc"
FileDataSource fds=new FileDataSource(FileName);
DataHandler dh=new DataHandler(fds);
String displayfilename="";
displayfilename = MimeUtility.encodeWord(DisplayFileName,"gb2312", null);//对显示名称进行编码,否则会出现乱码!
bodypart.setFileName(displayfilename);//可以和原文件名不一致
bodypart.setDataHandler(dh);
multipart.addBodyPart(bodypart);
由于javamail 的包里默认的对javax.activation.datasource只有两个实现:
分别是:filedatasource和urldatasource。
因此在webapp里为了不把上传的文件再保存为本地文件,然后再使用filedatasource,
写了一个实现了DdataSource的ByteDataSource,为了使用该类,我修改了网友莫琼写的
MoqUploadBean的上载组件来配合使用,从而实现不用将上传的文件保存为本地文件,
直接将上传文件保存为邮件的附件。具体发邮件的类请参考我前面写的文章
http://blog.csdn.net/wjw806/archive/2006/05/23/750794.aspx
//ByteDataSource.java 作者:汪建伟 该文件内容由汪建伟原创。转载请注明!
package sendmail;
/**
* <p>Title: </p>
* <p>Description: 发邮件</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: Peking University </p>
* @author 汪建伟
* @version 1.0
import javax.activation.DataSource;
import java.io.*;
public class ByteDataSource implements DataSource{
private byte[] filebyte=null;
private String filetype="application/octet-stream";
private String filename="";
private OutputStream outputstream=null;
private InputStream inputstream=null;
public ByteDataSource() {
}
public ByteDataSource(String FileName) {
File f=new File(FileName);
filename=f.getName();
try {
inputstream = new FileInputStream(f);
inputstream.read(filebyte);
} catch (Exception e) {
}
}
public ByteDataSource(byte[] filebyte,String displayfilename) {
this.filebyte=filebyte;
this.filename=displayfilename;
}
public String getContentType() {
return filetype;
}
public InputStream getInputStream() throws IOException {
InputStream input=new ByteArrayInputStream(filebyte);
return input;
}
public String getName() {
return filename;
}
public OutputStream getOutputStream() throws IOException {
outputstream.write(filebyte);
return outputstream;
}
}
//UploadFile.java 该文件是在网友莫琼的MoqUploadBean的基础上修改,可以将将从客户端传来的文件保存在byte[]中
package sendmail;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* Title: 文件上传类
* Description: 既能对文件进行上传,又能取得输入框的值,最多可同时上传255个文件
* Copyright: Copyright (c) 2002
* Company: Tekson
* @author 莫琼
* @modify 汪建伟修改 将从客户端传来的文件保存在byte[]中,便于其他用途,比如直接保存在数据库或加入发送邮件的附件中,就不需要临时文件了
* @version 1.1
*/
public class UploadFile {
private String[] sourceFile = new String[255]; //源文件名
private String[] suffix = new String[255]; //文件后缀名
private String canSuffix = "*";//".gif.jpg.png"; //可上传的文件后缀名,"*"表示可以上传任何文件
private ServletInputStream sis = null; //输入流
private String[] description = new String[255]; //描述状态
private long size = 1024 * 1024; //限制大小
private int count = 0; //已传输文件数目
private byte[] b = new byte[4096]; //字节流存放数组
private Object[] filebyte=new Object[255]; //存放上传文件内容为byte[]的一个数组
private boolean successful = true;
private Hashtable fields = new Hashtable();
public UploadFile() {
}
//设置上传文件的后缀名
public void setSuffix(String canSuffix) {
this.canSuffix = canSuffix;
}
//设置文件大小
public void setSize(long maxSize) {
this.size = maxSize;
}
//文件上传处理程序
public void setSourceFile(HttpServletRequest request) throws IOException {
sis = request.getInputStream();
int a = 0;
int k = 0;
String s = "";
while ( (a = sis.readLine(b, 0, b.length)) != -1) {
s = new String(b, 0, a);
if ( (k = s.indexOf("filename=/"")) != -1) {
// 取得文件数据
s = s.substring(k + 10);
k = s.indexOf("/"");
s = s.substring(0, k);
sourceFile[count] = s;
k = s.lastIndexOf(".");
suffix[count] = s.substring(k + 1);
if (canTransfer(count)) {
filebyte[count]=transferFile(count);
}
++count;
} else if ( (k = s.indexOf("name=/"")) != -1) {
// 普通表单输入元素,获取输入元素名字
String fieldName = s.substring(k+6, s.length()-3);
sis.readLine(b, 0, b.length);
StringBuffer fieldValue = new StringBuffer(b.length);
while ( (a = sis.readLine(b, 0, b.length)) != -1) {
s = new String(b, 0, a-2);
if ( (b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {
break;
} else {
fieldValue.append(s);
}
}
fields.put(fieldName, fieldValue.toString());
}
if (!successful)
break;
}
}
//取得表单元素值
public String getFieldValue(String fieldName) {
if (fields == null || fieldName == null) {
return null;
}
return (String) fields.get(fieldName);
}
//取得上传文件数
public int getCount() {
return count;
}
//取得源文件名
public String[] getSourceFile() {
return sourceFile;
}
//取得上传状态描述
public String[] getDescription() {
return description;
}
//取得上传文件的字节流,使用byte[]存储。
public Object[] getFilebyte(){
return filebyte;
}
//取得上传文件的后缀名。
public String[] getSuffix(){
return suffix;
}
//判断上传文件的类型
private boolean canTransfer(int i) {
suffix[i] = suffix[i].toLowerCase();
//这个是用来传图片的,各位可以把后缀名改掉或者不要这个条件
if ((sourceFile[i].equals(""))){
return false;
} else if (canSuffix.equals("*")){//可以上传任何类型文件
return true;
} else if (!(canSuffix.indexOf("."+suffix[i])>=0)) {
description[i] = "ERR: File suffix is wrong.";
return false;
}
else {
return true;
}
}
//上传文件转换
private byte[] transferFile(int i) {
ByteArrayOutputStream bufoutstream = new ByteArrayOutputStream();
try {
int a = 0;
long hastransfered = 0; //标示已经传输的字节数
String s = "";
while ( (a = sis.readLine(b, 0, b.length)) != -1) {
s = new String(b, 0, a);
if ( ( s.indexOf("Content-Type:")) != -1) {
break;
}
}
sis.readLine(b, 0, b.length);
while ( (a = sis.readLine(b, 0, b.length)) != -1) {
s = new String(b, 0, a);
if ( (b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {
break;
}
bufoutstream.write(b,0,a);
hastransfered += a;
if (hastransfered >= size) {
description[count] = "ERR: The file " + sourceFile[count] +
" is too large to transfer. The whole process is interrupted.";
successful = false;
break;
}
}
if (successful) {
description[count] = "Right: The file " + sourceFile[count] +
" has been transfered successfully.";
}
if (!successful) {
sis.close();
return null;
}
}
catch (IOException ioe) {
description[i] = ioe.toString();
return null;
}
return bufoutstream.toByteArray();
}
}
//sendmai.html
<html>
<head>
<title>JavaMail Client</title>
</head>
<body>
<form action="sendMailSubmit.jsp" enctype="MULTIPART/FORM-DATA" method="post">
To:<BR><input type=text name=to size=40>
<BR>From:<BR><input type=text name=from size=40>
<BR>Subject:<BR><input type=text name=subject size=40>
<BR>Content:<BR><textarea name=content rows=5 cols=50></textarea>
<br />
附件1:<input type="file" name="filename1" />
<br />
附件2:<input type="file" name="filename2" />
<br />
附件3:<input type="file" name="filename3" />
<br />
附件4:<input type="file" name="filename4" />
<br />
<BR><input type=submit value=Send><input type=reset>
</form>
</body>
</html>
//sendMailSubmit.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<%@ page import="sendmail.Mail"%>
<jsp:useBean id="fileBean" scope="page" class="sendmail.UploadFile" />
<%
fileBean.setSize(10000*1024);//限制上传文件大小
//fileBean.setSuffix(".gif.jpg.png.jpge.html.htm.bmp");//限制上传文件类型,"*"为不限制。
fileBean.setSuffix("*");
fileBean.setSourceFile(request);
String to=fileBean.getFieldValue("to");
String from=fileBean.getFieldValue("from");
String subject=fileBean.getFieldValue("subject");
String contect=fileBean.getFieldValue("content");
out.println("<br>收件人:" + fileBean.getFieldValue("to"));
out.println("<br>发件人:" + fileBean.getFieldValue("from"));
out.println("<br>主题:" + fileBean.getFieldValue("subject"));
out.println("<br>内容:" + fileBean.getFieldValue("content"));
String mto[]={to};
try{
Mail mymail= new Mail("smtp.163.com","yourname","yourpassword");
mymail.setMailFrom(from);
mymail.setSendDate(new java.util.Date());
mymail.setMailTo(mto,"to");
mymail.setSubject(subject);
mymail.addTextContext(contect);
mymail.addHtmlContext("html内容");
// mymail.addAttachmentFromUrl("http://www.pku.edu.cn","北大主页.htm");
// mymail.addAttachmentFromUrl("http://162.105.109.163/getimg?imgid=148","图片文件.jpg");
Object [] saFilebyte = fileBean.getFilebyte();
String [] saSourceFile = fileBean.getSourceFile();
int iCount = fileBean.getCount();
for(int i=0;i<iCount;i++) {
byte[] bb=(byte[])saFilebyte[i];
String str=saSourceFile[i];
File f=new File(str);
if (bb!=null) {
mymail.addAttachmentFrombyte(bb,f.getName());
}
}
mymail.sendMail() ;
out.println("<br>");
out.println("邮件发出!");
}
catch (Exception ex){
out.println("<br>");
out.println("邮件发送失败!"+ex.toString());
}
%>