浅谈JavaMail的应用之[文件下载打包并发送邮件的实现]


  文件的下载与压缩这一部分逻辑在业务的Servlet层来实现它.并调用邮件发送功能。

首先要用到两个jar包activation.jarmail.jar,这个如果没有可以网上下载一下。

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

List list = new ArrayList();
String[] path1 = new String[2];
//从硬盘获取要压缩的文件路径
path1[0] = "F:/测试/in1.xml";
path1[1] = "F:/测试/out1.xml";
list.add(path1);

String[] path2 = new String[2];
path2[0] = "F:/测试/in2.xml";
path2[1] = "F:/测试/out2.xml";
list.add(path2);
//================================================================================================
String gpIdAndNoStr = request.getParameter("gpIdAndNo");
String chosedReason = request.getParameter("chosedReason");
System.out.println("选择"+chosedReason+"模块");
//要生成压缩包的存储地址和文件名
//String desPath = "/本地磁盘路径/压缩文件名.zip";
//定义下载文件头
//response.setHeader("Content-Disposition", "attachment"+";filename="+gpIdAndNoStr+".zip");
//File zipFile = new File(desPath);
//获取上下文(当前项目的具有唯一性)
//String contextPath = request.getSession().getServletContext().getRealPath("/");
//返回此抽象路径的绝对路径的字符串
//File filepath = new File("");
//String contextPath = filepath.getAbsolutePath();
String ph = Thread.currentThread().getContextClassLoader().getResource("").getPath();
int num = ph.indexOf(".metadata");
String contextPath = ph.substring(1, num).replace('/', '\\')+request.getContextPath();
System.out.println("路径:"+contextPath);
//创建一个存放临时文件的目录
File tempFiles = new File(contextPath,"temp");
if(!tempFiles.exists()){
tempFiles.mkdirs();
}
//要生成压缩包的存储地址和文件名
//File tempFile = File.createTempFile(gpIdAndNoStr+"_", ".zip");
File tempFile = new File(tempFiles.getCanonicalPath()+"/"+gpIdAndNoStr+".zip");
if(!tempFile.exists()){
tempFile.createNewFile();
}
ZipOutputStream zipStream = null;
//创建输入流对象
FileInputStream zipSource = null;
//定义缓冲流
BufferedInputStream bufferStream = null;
//压缩条目不是具体的文件,而是压缩文件列表中的列表项。称为条目,就像索引一样
ZipEntry zipEntry = null;
//定义文件和目录路径的抽象表示形式
File file = null;
SimpleDateFormat sdf = new SimpleDateFormat();
//获取当前系统日期
Date date = new Date();
String dateStr = sdf.format(date);
int k =1;
try{
//构造最终压缩包的输出流
zipStream = new ZipOutputStream(new FileOutputStream(tempFile));
System.out.println("创建:"+tempFile.getAbsolutePath());
//zipStream = new ZipOutputStream(responce.getOutputStream());
for(int i=0; i
//通过List中获取的服务器文件下载路径,得到文件和目录路径名称的抽象表示形式的对象
file = new File(list.get(i)[0]);
//将要压缩的文件格式化为输入流
zipSource = new FileInputStream(file);
//定义压缩包中输入文件的文件名及目录
zipEntry = new ZipEntry(gpIdAndNoStr+"_"+dateStr+"_in_"+k+".xml");
//定义该压缩条目位置,开始写入文件到压缩包
zipStream.putNextEntry(zipEntry);
//输入缓冲流
bufferStream = new BufferedInputStream(zipSource,1024*4);
int len = 0;
//创建读写缓冲区
byte[] buf = new byte[1024*4];
//读入字节流
while((len = bufferStream.read(buf))!=-1){
zipStream.write(buf, 0, len);
}
//通过List中获取的服务器文件下载路径,得到文件和目录路径名称的抽象表示形式的对象
file = new File(list.get(i)[1]);
//将要压缩的文件格式化为输入流
zipSource = new FileInputStream(file);
//定义压缩包中输入文件的文件名及目录
zipEntry = new ZipEntry(gpIdAndNoStr+"_"+dateStr+"_out_"+k+".xml");
//定义该压缩条目位置,开始写入文件到压缩包
zipStream.putNextEntry(zipEntry);
//输入缓冲流
bufferStream = new BufferedInputStream(zipSource,1024*4);
//读入字节流
while((len = bufferStream.read(buf))!=-1){
zipStream.write(buf, 0, len);
}
k++;
}
//关闭流
zipStream.close();
bufferStream.close();
//此处调用邮件发送功能
SenderMail.createAttachMail(tempFile.getCanonicalPath(), gpIdAndNoStr);
//通过压缩包文件存储路径,得到文件和目录路径名的抽象表示形式的对象
File tpfile = new File(tempFile.getCanonicalPath());
//判断目录文件是否存在
if(tpfile.exists()){
//如果存在,则删除目录下的文件
tpfile.delete();
}

}catch(Exception e){
e.printStackTrace();
}finally {

try{
if(null != zipSource)
zipSource.close();
}catch(IOException e1){
e1.printStackTrace();
}
}

}

}

==============================================================

这个类就是实现邮件的发送功能的java代码了,上面的那个类会调用这个类的方法。

package sendmail;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SenderMail {
//初始化
private static Properties prop = null;
static{
  prop = new Properties();
  InputStream inputStream =
  SenderMail.class.getClassLoader().getResourceAsStream("email.properties");
try {
  prop.load(inputStream);
} catch (IOException e) {
  e.printStackTrace();
}
}

@SuppressWarnings("static-access")
public static MimeMessage createAttachMail(String sendpath,String gpIdAndNo)

   throws MessagingException, FileNotFoundException, IOException{
//未设置配置文件的写法
//prop = new Properties();
//prop.setProperty("mail.host","smtp.firsttech-soft.com");
//prop.setProperty("smtp","mail.transport.protocol");
//prop.setProperty("mail.smtp.auth","true");

//使用JavaMail发送邮件的5个步骤
//1.创建Session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过Session得到transport对象
Transport ts = session.getTransport();

//连上邮件服务器(不需要设置用户名/密码)
// ts.connect(prop.getProperty("mail.host"),
// prop.getProperty("user"),
// prop.getProperty("password")
// );

//3.连上邮件服务器(不需要设置用户名/密码)
ts.connect();
//4.创建邮件
MimeMessage message = new MimeMessage(session);
//设置邮件基本信息
//发件人
message.setFrom(new InternetAddress(prop.getProperty("from")));

//单个收件人
//message.setRecipient(Message.RecipientType.TO, new InternetAddress(prop.getProperty("recipient")));
//设置收件人们
//通过配置文件,得到收件人地址数组对象
//String[] addressstr = prop.getProperty("recipient").split(",");
//创建一个数组对象,用于存储收件人地址
//InternetAddress[] address = new InternetAddress[addressstr.length];
//for(int i=0;i // address[i] = new InternetAddress(addressstr[i]);
//}
//message.setRecipients(RecipientType.TO, address);

//设置收件/抄送人们
//通过配置文件得到收件人地址数组对象
InternetAddress[]
sendAddress = new InternetAddress().parse(prop.getProperty("ccmail"));
message.setRecipients(RecipientType.TO, sendAddress);
//通过配置文件,得到抄送人地址数组对象
InternetAddress[]
ccAddresses = new InternetAddress().parse(prop.getProperty("recipient"));
message.setRecipients(RecipientType.CC, ccAddresses);
//邮件标题
message.setSubject(gpIdAndNo+"文件");
//创建邮件正文,为了避免正文乱码,需要用charset=utf-8指明字符编码
MimeBodyPart text = new MimeBodyPart();
StringBuffer strbuf = new StringBuffer();
strbuf.append("您好!
");

strbuf.append("    你查询下载的附件请见附件。
");

strbuf.append("谢谢!
");

text.setContent(strbuf.toString(),"text/html;charset=utf-8");
//创建邮件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(sendpath));
attach.setDataHandler(dh);
attach.setFileName(dh.getName());
//创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");

message.setContent(mp);
message.saveChanges();
//将创建的Email写入到E盘存储
message.writeTo(new FileOutputStream(prop.getProperty("localdiskpath")));
//发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
//返回生成邮件
return message;

}
}

======================================================

邮件发送的相关配置参数见email.properties这个文件:

mail.host=smtp.abc-soft.com
mail.transport.protocol=smtp
from=xxxxx@abc-soft.com
#user=xxxxx
#password=******
#mail.smtp.auth=true
recipient=xxxxx@abc-soft.com
ccmail=xxxxx@abc-soft.com
localdiskpath=E:/Email/attachMail.eml

=======================================================

  好到这里整个文件下载,压缩打包,并将压缩文件用邮件发送出去

就完成了。但是我遇到一个问题,在局域网环境下用Foxmail邮箱试了完全ok,

但是用外网时我用自己的qq邮箱试了一下会报

com.sun.mail.smtp.SMTPAddressFailedException: [EOF]这个异常.

可能是邮箱服务器不让连。有解决方法可以告诉我哦哈哈。