⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 parsemimemessage.java

📁 电子邮件收发系统,采用各种技术进行研究开发适用大学生课程设计
💻 JAVA
字号:
package net.meybo.mail.client;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.*;
import javax.mail.internet.*;

import org.apache.log4j.Logger;

import com.easyjf.util.HtmlUtil;
public class ParseMimeMessage {
private MimeMessage mimeMessage;
private  String dateformat="yyyy-MM-dd hh:mm";
private String content;
private boolean html;
private boolean needEncoding=false;
private static final Logger logger = (Logger) Logger.getLogger(ParseMimeMessage.class.getName());
public ParseMimeMessage()
{
	
}
public ParseMimeMessage(MimeMessage mimeMessage)
{
	this.mimeMessage=mimeMessage;
}
public boolean isHtml() throws Exception
{

	if(content==null)content=getMailContent((Part)mimeMessage);
	return html;	
}
/** 
 * 获得发件人的地址和姓名 
 */ 
public String getFrom()throws Exception{ 
    InternetAddress address[] = (InternetAddress[])mimeMessage.getFrom();
    if(address==null)return null;
    String from = address[0].getAddress(); 
    if(from == null) from=""; 
    String personal =address[0].getPersonal(); 
    if(personal!= null)personal=MimeUtility.decodeText(personal);   
    String fromaddr =personal==null?from:personal+"<"+from+">"; 
    return needEncoding?new String(fromaddr.getBytes("iso8859-1"),"gbk"):fromaddr; 
} 

/** 
 * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 
 * "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址 
 */ 
public String getMailAddress(String type)throws Exception{ 
    String mailaddr =null; 
    String addtype = type.toUpperCase(); 
    InternetAddress []address = null; 
    if(addtype.equals("TO") || addtype.equals("CC") ||addtype.equals("BCC")){ 
        if(addtype.equals("TO")){ 
            address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.TO);            
        }else if(addtype.equals("CC")){ 
            address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.CC); 
        }else{ 
            address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.BCC); 
        } 
        if(address != null){ 
            for(int i=0;i<address.length;i++){ 
                String email=address[i].getAddress();               
                String personal=address[i].getPersonal();               
                String compositeto=(personal!=null)?personal+"<"+email+">":email;
                if(mailaddr==null)mailaddr=compositeto;
                else mailaddr+=","+compositeto;               
            } 
           // mailaddr=mailaddr.substring(1); 
        } 
    }else{ 
        throw new Exception("Error emailaddr type!"); 
    } 
    return mailaddr; 
} 
 
/** 
 * 获得邮件主题 
 */ 
public String getSubject()throws MessagingException{ 
    String subject = ""; 
    try{ 
        subject =MimeUtility.decodeText(mimeMessage.getSubject());
    }catch(Exception exce){
    	logger.error("读取邮件标题出错:"+exce);
    } 
    return subject; 
} 
 
/** 
 * 获得邮件发送日期 
 */ 
public String getSentDate()throws Exception{ 
   Date sentdate = mimeMessage.getSentDate(); 
    SimpleDateFormat format = new SimpleDateFormat(dateformat); 
    return format.format(sentdate); 
} 
public String getMailContent() throws Exception
{	
	
	if(content==null)content=getMailContent((Part)mimeMessage);
	//System.out.println(new String(content.getBytes("iso8859-1"),"gbk"));
	//System.out.println("正文编码:"+(mimeMessage.getEncoding()==null));
	return content;//mimeMessage.getEncoding()==null?content:new String(content.getBytes("iso8859-1"),"gbk");
}

/** 获取邮件正文
 * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 
 * 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析 
 */ 
public String getMailContent(Part part)throws Exception{
	StringBuffer bodyText=new StringBuffer();
    String contenttype = part.getContentType();
    int nameindex = contenttype.indexOf("name"); 
    boolean conname =false; 
    if(nameindex != -1) conname=true; 
  
    try{
    if(part.isMimeType("text/plain") && !conname){    	
    	String text=(String)part.getContent();
    	text=HtmlUtil.escapeHTMLTag(text);    	
        bodyText.append(text); 
    }else if(part.isMimeType("text/html") && !conname){
    	String cont=(String)part.getContent();
    	 //System.out.println("CONTENTTYPE: "+contenttype+part.getClass()); 
    	if(part instanceof MimeBodyPart || part instanceof MimeMessage)
    	{
    		String encoding="";
    		if(part instanceof MimeBodyPart)
    			encoding=((MimeBodyPart)part).getEncoding().toLowerCase();
    		else
    			encoding=((MimeMessage)part).getEncoding().toLowerCase();    		
    		if(encoding!=null && encoding.equals("8bit"))
    		{    	   
    		cont=new String(cont.getBytes("iso8859-1"),"gbk");
    		needEncoding=true;
    		}    	
    	}    	
    	bodyText.append(cont);
        html=true;
    }else if(part.isMimeType("multipart/*")){ 
        Multipart multipart = (Multipart)part.getContent(); 
        int counts = multipart.getCount(); 
        for(int i=0;i<counts;i++){ 
            bodyText.append(getMailContent(multipart.getBodyPart(i))); 
        } 
    }else if(part.isMimeType("message/rfc822")){ 
        getMailContent((Part)part.getContent()); 
    }else{
    	//System.out.println(part.getContentType());
    	logger.warn("未知的邮件内容!"+part.getContentType()+":"+part.getClass());
    } 
    }
    catch(Exception e)
    {
    	logger.error("邮件解析错误!"+e);
    }
    return bodyText.toString();
} 

/** 
 * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false" 
 */ 
public boolean getReplySign()throws MessagingException{ 
    boolean replysign = false; 
    String needreply[] = mimeMessage.getHeader("Disposition-Notification-To"); 
    if(needreply != null){ 
        replysign = true; 
    } 
    return replysign; 
} 

/** 
 * 获得此邮件的Message-ID 
 */ 
public String getMessageId()throws MessagingException{ 
    return mimeMessage.getMessageID(); 
} 
 
/** 
 * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】 
 */ 
public boolean isNew()throws MessagingException{ 
    boolean isnew = false; 
    Flags flags = ((Message)mimeMessage).getFlags(); 
    Flags.Flag []flag = flags.getSystemFlags();
    for(int i=0;i<flag.length;i++){ 
        if(flag[i] == Flags.Flag.SEEN){ 
            isnew=true;
            break; 
        } 
    } 
    return isnew; 
} 

public boolean isContainAttach()throws Exception
{
	return isContainAttach((Part)mimeMessage);
}
/** 
 * 判断此邮件是否包含附件 
 */ 
public boolean isContainAttach(Part part)throws Exception{ 
    boolean attachflag = false;
    if(part.isMimeType("multipart/*")){ 
        Multipart mp = (Multipart)part.getContent(); 
        for(int i=0;i<mp.getCount();i++){ 
            BodyPart mpart = mp.getBodyPart(i); 
            String disposition = mpart.getDisposition(); 
            if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))) 
                attachflag = true; 
            else if(mpart.isMimeType("multipart/*")){ 
                attachflag = isContainAttach((Part)mpart); 
            }else{ 
                String contype = mpart.getContentType(); 
                if(contype.toLowerCase().indexOf("application") != -1) attachflag=true; 
                if(contype.toLowerCase().indexOf("name") != -1) attachflag=true; 
            } 
        } 
    }else if(part.isMimeType("message/rfc822")){ 
        attachflag = isContainAttach((Part)part.getContent()); 
    } 
    return attachflag; 
} 
public InputStream getAttach(String fileName) throws Exception
{
	return getAttach((Part)mimeMessage,fileName);
}
public InputStream getAttach(Part part,String fileName) throws Exception{
	     InputStream in=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 = mpart.getDisposition(); 
	            if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
	            
	                String file =MimeUtility.decodeText(mpart.getFileName());
	                //if(!needEncoding)file=new String(file.getBytes("iso8859-1"),"gbk");
	                if(file.toLowerCase().equals(fileName.toLowerCase()))
	                {
	                in= mpart.getInputStream();	                
	                }
	            }else if(mpart.isMimeType("multipart/*")){ 
	               in= getAttach(mpart,fileName); 	           
	        } 
	        }
	    }else if(part.isMimeType("message/rfc822")){ 
	    	in=getAttach((Part)part.getContent(),fileName); 
	    } 
	return in;
}
public List getAttachMent() throws Exception
{
	return getAttachMent((Part)mimeMessage);
}
/** 
 * 【保存附件】 
 */ 
public List getAttachMent(Part part)throws Exception{ 
    String fileName = "";
    List list=new ArrayList();    
    
    if(part.isMimeType("multipart/*")){ 
        Multipart mp = (Multipart)part.getContent(); 
        for(int i=0;i<mp.getCount();i++){ 
            BodyPart mpart = mp.getBodyPart(i); 
            String disposition = mpart.getDisposition();
           System.out.println("附件:"+part.getContentType()+":"+disposition);
            if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
            	Map map=new HashMap();            	
                fileName =MimeUtility.decodeText(mpart.getFileName());                
            	//fileName =mpart.getFileName();
                //System.out.println(((MimeBodyPart)mpart).getEncoding());
                //if(!needEncoding)fileName=new String(fileName.getBytes("iso8859-1"),"gbk");
                map.put("fileName",fileName);
                String imgExt=fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();
                if(imgExt.equalsIgnoreCase("JPG"))
                    imgExt = "jpg.gif";
                  else if(imgExt.equalsIgnoreCase("GIF"))
                    imgExt = "gif.gif";
                  else if(imgExt.equalsIgnoreCase("DOC"))
                    imgExt = "Word.gif";
                  else if(imgExt.equalsIgnoreCase("XLS") || imgExt.equalsIgnoreCase("CSV") )
                    imgExt = "Excel.gif";               
                  else if(imgExt.equalsIgnoreCase("PDF"))
                    imgExt = "pdf.gif";
                  else if(imgExt.equalsIgnoreCase("TXT"))
                    imgExt = "txt.gif";
                  else if(imgExt.equals("RAR")||imgExt.equals("ZIP"))
                  {
                	  imgExt="img_rar.gif";
                  }
                  else
                    imgExt = "binary.gif";
                map.put("img",imgExt);
                //map.put("in",mpart.getInputStream());                
                map.put("description",mpart.getDescription()!=null?mpart.getDescription(): fileName);              	
                int size=mpart.getInputStream().available()/1024;
               // System.out.println("附件名称:"+needEncoding+fileName+new String(fileName.getBytes("iso8859-1"),"gbk"));
                String unit="";
                if(size!=0){
                if(size/1024>1)
                {   
                	DecimalFormat df=new DecimalFormat(".00");                	
                	unit=df.format(size/1024f)+"M";
                }
                else unit=size+"K";
                }
                else
                {
                	unit=mpart.getInputStream().available()+"Bytes";
                }
                
                map.put("size",unit);
                list.add(map);
                //if(fileName.toLowerCase().indexOf("gb2312") != -1){ 
                  //  fileName = MimeUtility.decodeText(fileName); 
               // } 
                 //saveFile(fileName,mpart.getInputStream()); 
            }else if(mpart.isMimeType("multipart/*")){ 
               list.addAll(getAttachMent(mpart)); 
            }else{ 
                fileName = mpart.getFileName(); 
                if((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)){ 
                    fileName=MimeUtility.decodeText(fileName); 
                  //  saveFile(fileName,mpart.getInputStream()); 
                } 
            } 
        } 
    }else if(part.isMimeType("message/rfc822")){ 
    	list.addAll(getAttachMent((Part)part.getContent())); 
    } 
    return list;
} 

/** 
 * 【设置日期显示格式】 
 */ 
public void setDateFormat(String format)throws Exception{ 
    this.dateformat = format; 
}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -