8d874e48bc2a1a864e31b19248daab4948198bfb.svn-base 10.6 KB
package com.espeed.tool;

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

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 sun.misc.BASE64Decoder;

import com.espeed.pojo.YxySendMailMasterBase;

/***
 * 
 * @author xieyong
 * 邮件解析
 */
public class AnalysisYxyMail {


	private  MimeMessage msg;
	private StringBuffer bodyText=new StringBuffer();
	public String attrName="";
	public String context="";
	String servicepath="";
	//定义结果集
	List<String> result=new ArrayList<String>();
	//解析邮件(本地)
	public List ParseEmlMethod(YxySendMailMasterBase master,String emlpath)throws Exception{
		//定义结果集
		List<String> result=new ArrayList<String>();
		//项目路径
		servicepath = this.getClass().getClassLoader().getResource("/").getPath();
		servicepath = servicepath.substring(1, servicepath.length());
		servicepath = servicepath.replace("/WEB-INF/classes/","");
		String emlFilePath=master.getEml_file_path().replace("#####", emlpath);			
		//判断是否之前的有加密的key
		if(master.getEml_encode_key()!=null&&!master.getEml_encode_key().equals("")){
			//解密邮件
			BASE64Decoder enc=new BASE64Decoder();
			 //需要一个流 给它解密的流
			CipherInputStream CStream = null;				
			CStream =(CipherInputStream) Encrypt.decrypt(emlFilePath,Encrypt.toKey(enc.decodeBuffer(master.getEml_encode_key())));
			Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
			msg = new MimeMessage(mailSession, CStream);
		}else{//未加密的
			InputStream is =new FileInputStream(emlFilePath);
			Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
			msg = new MimeMessage(mailSession, is);
			is.close();			
		}

		//获取内容
		getMailContent((Part) msg);
		context=bodyText+"";			
		//解析附件与图片
		saveAttachMent((Part) msg,master);		
		result.add(attrName);
		result.add(context);
		return result;
	}
		
	//解析邮件(webservice)
	public List ParseEmlWebService(YxySendMailMasterBase master,String emlcode)throws Exception{
		//定义结果集
		List<String> result=new ArrayList<String>();
		
		//字符串转流
		InputStream is = new ByteArrayInputStream(emlcode.getBytes());
		Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
		msg = new MimeMessage(mailSession, is);
		is.close();			

		//获取内容
		getMailContent((Part) msg);
		context=bodyText+"";			
		//解析附件与图片
		saveAttachMent((Part) msg,master);		
		result.add(attrName);
		result.add(context);
		return result;
	
	}
	
	//获取内容
	public void getMailContent(Part part) throws Exception {
		String contenttype = part.getContentType();
		String pageEcoding="GBK";
		if(contenttype!=null&&contenttype!=""&&contenttype.indexOf("charset")!=-1){
			int begin=contenttype.indexOf("charset=");
			pageEcoding=contenttype.substring(begin+8).replaceAll("\"", "");
		}
		if(!pageEcoding.toLowerCase().equals("utf-8")
				&&!pageEcoding.toLowerCase().equals("gbk")
				&&!pageEcoding.toLowerCase().equals("iso-8859-1")
				&&!pageEcoding.toLowerCase().equals("big5")
				&&!pageEcoding.toLowerCase().equals("windows-1251")){
			pageEcoding="GBK";
		}
		
		if(pageEcoding.equals("gb2312")){
			pageEcoding="GBK";
		}
		
		
		
		int nameindex = contenttype.indexOf("name");
		boolean conname = false;
		if (nameindex != -1)
			conname = true;
		
		if (part.isMimeType("text/html") && !conname) {
			if(!bodyText.toString().equals("")){
				bodyText=new StringBuffer();
			}
			
			BufferedReader bis =null;
			bis= new BufferedReader(new InputStreamReader(part.getInputStream(),pageEcoding));			
			StringBuffer context=new StringBuffer();
			String line = null;   
		    while ((line = bis.readLine()) != null) {  
		    	context.append(line);
		    }
			bodyText.append(context);	
			
		}else if(part.isMimeType("text/plain") && !conname){
			BufferedReader bis =null;
			bis= new BufferedReader(new InputStreamReader(part.getInputStream(),pageEcoding));			
			StringBuffer context=new StringBuffer();
			String line = null;   
		    while ((line = bis.readLine()) != null) {  
		    	context.append(line);
		    }  						
			bodyText.append(context);	
			
		}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,YxySendMailMasterBase master)throws Exception{ 		
		String fileName = "";//文件名
		boolean isPic=false;
		String [] contentid=null;//是否有图片ID
    	if(part.isMimeType("multipart/*")){
    		Multipart mp = (Multipart) part.getContent();
    			for(int i=0;i<mp.getCount();i++){
    				BodyPart mpart = mp.getBodyPart(i);
    				String fujianType=mpart.getContentType();
    				String disposition="";
   		            if(fujianType.indexOf("application/octet-stream")!=-1){
   		            	String[] a=mpart.getHeader("Content-Disposition");
   		            	if(a!=null){
   		            		for(int s=0;s<a.length;s++){
	   		            		if(a[s].indexOf("attachment")!=-1){
	   		            			disposition="attachment";
	   		            			break;
	   		            		}
	   		            	}	
   		            	}
   		            	
   		            }
   		            disposition = mpart.getDisposition();
   		            if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
						fileName = mpart.getFileName();
						contentid=mpart.getHeader("Content-ID");
						if(contentid!=null){//说明是图片
							isPic=true;
						}else{
							isPic=false;
						}
						saveFile(fileName,mpart.getInputStream(),isPic,master);
   		            }else if(mpart.isMimeType("multipart/*")){
   		            	saveAttachMent(mpart,master);
   		            }else if(mpart.isMimeType("message/rfc822")){
	            		fileName = mpart.getFileName();
	            		contentid=mpart.getHeader("Content-ID");
						if(contentid!=null){//说明是图片
							isPic=true;
						}else{
							isPic=false;
						}
	            		if(fujianType.indexOf("text/html")!=-1||fujianType.indexOf("text/plain")!=-1){
	    					continue;
	    				}else{
	    					saveFile(fileName,mpart.getInputStream(),isPic,master);
	    				}
   		           }
    			}
    		}else if(part.isMimeType("message/rfc822")){
    			saveAttachMent((Part)part.getContent(),master);
    		}else if(part.isMimeType("application/octet-stream")){
    			fileName=part.getFileName();
    			contentid=part.getHeader("Content-ID");
				if(contentid!=null){//说明是图片
					isPic=true;
				}else{
					isPic=false;
				}	
    			saveFile(fileName,part.getInputStream(),isPic,master);
    		}
	 } 
	
	//真正的保存附件到指定目录(保存附件)	  
	private void saveFile(String fileName,InputStream in,boolean isPic,YxySendMailMasterBase master)throws Exception{   
		//图片保存
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
		String nowFileName=df.format(new Date())+GetRandom.getRandomString(10);			
		//附件名编码解析
		if(fileName.contains("=?")||fileName.contains("?B")){
			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 picAndAttr="";
		if(isPic){//解析图片
			picAndAttr="pic";
			//分割出图片后缀
			String[] fileEx=fileName.split("\\.");
			if(fileEx.length>=2){
				fileName=nowFileName+"."+fileEx[1];
			}else{
				fileName=nowFileName;
			}				
		}else if(!isPic){//解析附件
			picAndAttr="attachment";
		}else{
			return;
		}
		String osName = System.getProperty("os.name");   
	    String storedir =path()+"/mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/"+picAndAttr;
	   
	    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 {
		String []houzhui=fileName.split("\\.");
		if(houzhui.length>=2){
			nowFileName=(nowFileName+"."+houzhui[1]);
		}
		if(!isPic){
			attrName+=(nowFileName+"#####"+fileName)+",";
		}
		File isfileExite = new File(storefile+"/"+nowFileName);
		if(!isfileExite.exists()){
		  bos = new BufferedOutputStream(new FileOutputStream(storefile+"/"+nowFileName));  
		  bis = new BufferedInputStream(in);  
		  int c;  
		  while ((c = bis.read()) != -1) {  
		     bos.write(c);  
		     bos.flush();  
		  }  
		}
	  
	} finally {  
	     if(bos!=null){
	         bos.close();
	         bis.close();  
	     }  
	            
	}		        
	      //如果是图片则替换图片路径
			if(isPic){
				//cid的位置
				int cidwhere=context.indexOf("cid");
				if(cidwhere!=-1){
					String str=context.substring(cidwhere,context.length());
					int next=str.indexOf("/>");
					String newStr="";
					if(next==-1){
						next=str.indexOf("'");
						
					}
					newStr=context.substring(cidwhere,(next-1)+cidwhere);
					context=context.replace(newStr, "mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/pic/"+nowFileName+"\"");
					//result.set(0, context);
				}else{
					context=context+"</br><img src=/mailtempfile/"+master.getUser_domain()+"/"+master.getUser_loginid()+"/pic/"+nowFileName+"></img>";
				}
			}		
} 

	
	//获得系统相对路径
	public String path(){;
		String pathew = this.getClass().getClassLoader().getResource("/").getPath();
		pathew = pathew.substring(1, pathew.length());
		pathew = pathew.replace("/WEB-INF/classes/","");
		return   pathew;
	}


}