b88fa3e6a41496be7d70c36d8a22dae3a0174faa.svn-base 8.8 KB
package yxy.timer.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
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.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/***
 * 
 * @author xieyong
 * 邮件解析
 * 解析到营销web路径下,提供图片路径进行展示.
 */
public class AnalysisYxyMail {
	private  MimeMessage msg;
	private StringBuffer bodyText=new StringBuffer();
	public String attrName="";
	public String context="";
	//定义结果集
	List<String> result=new ArrayList<String>();
	//解析邮件,返回内容,图片名与附件名(存放名+"#####"+真实名)
	public List<String> ParseEmlMethod(String emlpath)throws Exception{
		//定义结果集
		List<String> result=new ArrayList<String>();
		result.add("");//内容
		result.add("");//附件
		//读取eml
		InputStream is =new FileInputStream(emlpath);
		Session mailSession = Session.getDefaultInstance(System.getProperties(), null);
		msg = new MimeMessage(mailSession, is);
		is.close();			
		
		//获取内容
		getMailContent((Part) msg);
		context=bodyText+"";
		//解析附件与图片
		saveAttachMent((Part) msg);
		result.set(0,context);
		result.set(1,attrName);
		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());
		}
	}
	
	//解析附件与图片   
	public void saveAttachMent(Part part)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);
   		            }else if(mpart.isMimeType("multipart/*")){
   		            	saveAttachMent(mpart);
   		            }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);
	    				}
   		           }
    			}
    		}else if(part.isMimeType("message/rfc822")){
    			saveAttachMent((Part)part.getContent());
    		}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);
    		}
	 } 
	
	//真正的保存附件到指定目录(保存附件)	  
	private void saveFile(String fileName,InputStream in,boolean isPic)throws Exception{   
		//图片保存
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String nowFileName=df.format(new Date());			
		//附件名编码解析
		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()+"/webmailtemp/"+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){
			System.out.println("有图片了");
			String yxytimeurl=ConfigPath.getYxytimeUrl();
			//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, yxytimeurl+"/webmailtemp/pic/"+nowFileName+"\"");
			}else{
				context=context+"</br><img src="+yxytimeurl+"/webmailtemp/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;
	}


}