75c10f3358b969df4c81153ac92896b580e11f04.svn-base 9.5 KB
package com.espeed.yxy.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.crypto.CipherInputStream;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.espeed.yxy.tool.Encrypt;

import sun.misc.BASE64Decoder;

/**
 * 程序名称:    	EspeedMail_时速邮箱
 * 程序版本:    	V1.0
 * 作    者:    	深圳市科飞时速网络技术有限公司(0755-88843776)
 * 版权所有:    	深圳市科飞时速网络技术有限公司
 * 技术支持:    	Tech@21gmail.com
 * 单元名称:     解析邮件(营销游)
 * 开始时间:    	2013.12.09
 * 程 序 员:    	谢勇
 * 最后修改:    
 * 备    注:		如需修改请通知程序员    
 */
public class AnalysisMail {

	private  MimeMessage msg;
	private StringBuffer bodyText=new StringBuffer();
	public String attrname="";
	/**解析邮件*/
	public List ParseEmlMethod(String path,String key){
		//定义结果集
		List<String> result=new ArrayList<String>();
		try {
			//System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");
			if(key!=null&&!key.equals("")){
				//解密邮件
				BASE64Decoder enc=new BASE64Decoder();
				 //需要一个流 给它解密的流
				CipherInputStream CStream = null;
				CStream =(CipherInputStream) Encrypt.decrypt(path,Encrypt.toKey(enc.decodeBuffer(key)));

				Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
				msg = new MimeMessage(mailSession, CStream);
			}else{
				InputStream is =new FileInputStream(path);
				Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
				msg = new MimeMessage(mailSession, is);
			}
			
			
			//获取内容
			getMailContent((Part) msg);
			result.add(bodyText+"");
			//saveAttachMent((Part) msg);
			//result.add(attrName);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**解析附件或图片*/
	public String parsePicOrAttr(String emlpath,String key,int check,String savepath){
		try {
			attrname="";
			if(key!=null&&!key.equals("")){
				//解密邮件
				BASE64Decoder enc=new BASE64Decoder();
				 //需要一个流 给它解密的流
				CipherInputStream CStream = null;
				CStream =(CipherInputStream) Encrypt.decrypt(emlpath,Encrypt.toKey(enc.decodeBuffer(key)));

				Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
				msg = new MimeMessage(mailSession, CStream);
			}else{
				InputStream is =new FileInputStream(emlpath);
				Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
				msg = new MimeMessage(mailSession, is);
			}
			//处理图片与附件
			saveAttachMent((Part)msg,check,savepath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return attrname;
	}
	
	/**获取内容*/
	public void getMailContent(Part part) throws Exception {
		String contenttype = part.getContentType();
		int nameindex = contenttype.indexOf("name");
		boolean conname = false;
		if (nameindex != -1)
			conname = true;
		
		if (part.isMimeType("text/plain") && !conname) {
			bodyText.append(part.getContent());
	
		} else if (part.isMimeType("text/html") && !conname) {
			bodyText.append(part.getContent());
		
		} else if (part.isMimeType("multipart/*")) {
			Multipart multipart = (Multipart) part.getContent();
			int counts = multipart.getCount();
			for (int i = 0; i < counts; i++) {
				getMailContent(multipart.getBodyPart(i));
			}
		
		} else if (part.isMimeType("message/rfc822")) {
			getMailContent((Part) part.getContent());
			
		} else {
			
		}
	}
	
	/**附件与图片*/     
	public void saveAttachMent(Part part,int check,String savepath) { 
		try {
			boolean isPic=false;
			String filename="";
			String [] contentid=null;//是否有图片
	    	if(part.isMimeType("multipart/*")){
	    		Multipart mp = (Multipart)part.getContent();
	    			for(int i=0;i<mp.getCount();i++){
	    				BodyPart mpart = mp.getBodyPart(i);
	    				String disposition="";
	   		            disposition = mpart.getDisposition();
	   		            if((disposition != null) &&((disposition.equals(Part.ATTACHMENT))||(disposition.equals(Part.INLINE)))){
	   		            	filename = mpart.getFileName();
							filename = MimeUtility.decodeText(filename);
							//是否是图片
							contentid=mpart.getHeader("Content-ID");
							if(contentid!=null){//说明是图片
								isPic=true;
							}
							//判断是解析图片还是附件
							if(check==1){//附件
								if(!isPic){
									saveFile(filename,mpart.getInputStream(),savepath,check);
								}
							}else{//图片
								if(isPic){
									saveFile(filename,mpart.getInputStream(),savepath,check);
								}
							}
   		            	}else if(mpart.isMimeType("multipart/*")){
   		            		saveAttachMent(mpart,check,savepath);
   		            	}else if(mpart.isMimeType("message/rfc822")){
   		            		filename = mpart.getFileName();
	            			filename=MimeUtility.decodeText(filename);
	            			//是否是图片
							contentid=mpart.getHeader("Content-ID");
							if(contentid!=null){//说明是图片
								isPic=true;
							}
							//判断是解析图片还是附件
							if(check==1){//附件
								if(!isPic){
									saveFile(filename,mpart.getInputStream(),savepath,check);
								}
							}else{//图片
								if(isPic){
									saveFile(filename,mpart.getInputStream(),savepath,check);
								}
							}
   		            	}
	    			}
	    		}else if(part.isMimeType("message/rfc822")){
	    			saveAttachMent((Part)part.getContent(),check,savepath);
	    		}else if(part.isMimeType("application/octet-stream")){
	    			filename=part.getFileName();
	    			contentid=part.getHeader("Content-ID");
	    			if(contentid!=null){//说明是图片
						isPic=true;
					}
					//判断是解析图片还是附件
					if(check==1){//附件
						if(!isPic){
							saveFile(filename,part.getInputStream(),savepath,check);
						}
					}else{//图片
						if(isPic){
							saveFile(filename,part.getInputStream(),savepath,check);
						}
					}
	    		}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("erro:保存附件异常!");
		}
	} 
	
	/**真正的保存附件到指定目录*/  
	private void saveFile(String fileName,InputStream in,String savepath,int check){   
		try {
			//重新取名
			String savaname="";//指定保存的名字
			//时间命名
			SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String nowtime=df.format(new Date());
			savaname=nowtime;
			
			String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";   //生成字符串从此序列中取
	        Random random = new Random();   
	        StringBuffer sb = new StringBuffer();   
	        for (int i=0;i<5;i++) {   
	            int number = random.nextInt(base.length());   
	            sb.append(base.charAt(number));   
	        }
	        savaname+=sb.toString();
	        
			//附件名编码解析
			if(fileName.contains("=?")||fileName.contains("?B")){
				fileName=fileName.replace(" ", "");
				fileName=MimeUtility.decodeText(fileName);
    		}else{
    			String newstr=fileName.replace("?", "");
    			newstr=new String(newstr.getBytes("iso-8859-1"));
    			if(!newstr.contains("?")){
    				fileName=new String(fileName.getBytes("iso-8859-1"));
    			}	
    		}
			//取得文件后缀
			String[] typearry=fileName.split("\\.");
			String filetype=typearry[typearry.length-1];
			//如果是图片则使用新随即名称
	        if(check==1){//附件
	        	attrname+=savaname+"."+filetype+"#####"+fileName+",";
	        }else{//图片
	        	attrname+=savaname+"."+filetype+"#####";
	        }
			String osName = System.getProperty("os.name");   
		    String storedir = savepath;
		    String separator = "";   
		    if (osName == null)   
		    osName = "";
		    if (osName.toLowerCase().indexOf("win") != -1) {   
		    	separator = "\\";  
		    	if (storedir == null || storedir.equals(""))  
		    		storedir = "c:\\tmp";  
		    }else {  
		    	separator = "/";  
		    	storedir = "/tmp";  
		    }  
		    File storefile = new File(storedir + separator);  
		    if(!storefile.exists()){
		    	storefile.mkdirs();
		    }
		    BufferedOutputStream bos = null;  
		    BufferedInputStream bis = null;  
		    try {  
			    bos = new BufferedOutputStream(new FileOutputStream(storefile+"//"+ savaname+"."+filetype));  
			    bis = new BufferedInputStream(in);  
			    int c;  
			    while ((c = bis.read()) != -1) {  
			        bos.write(c);  
			        bos.flush();  
			    }  
		    }catch (Exception exception) {  
		    	exception.printStackTrace();   
		    }finally {  
		    	bos.close();  
		    	bis.close();  
		    }  
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("erro:保存附件到指定目录异常!");
		}	
	} 
	
    /**获得系统相对路径*/
	public String path(){;
		String pathew = this.getClass().getClassLoader().getResource("/").getPath();
		pathew = pathew.substring(1, pathew.length());
		pathew = pathew.replace("/WEB-INF/classes/","");
		return   pathew;
	}
	
	public static void main(String[] args) {
		AnalysisMail paxlmail=new AnalysisMail();
		List result = paxlmail.ParseEmlMethod("f:\\emily20161221170720.eml","");
	}
}