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

📄 emailreceiver.java

📁 使用javamail接收邮件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
    	
        try
        {
            // 得到标头信息
           // String from = ((InternetAddress)message.getFrom()[0]).getPersonal();
        	String from = null;
        	String address = "";
        	
        	String replay="";
        	try{
        		replay=message.getAllRecipients()[0].toString();
        	}catch(Exception ex){
        		replay="";
        	}
        	
        	
        	try{
	           	 if(replay.indexOf("=?x-unknown?") >=0){
	           		replay = replay.replaceAll("x-unknown","gbk" ); 
	           		replay = MimeUtility.decodeText(replay);
	           	 }else{
	           		replay = MimeUtility.decodeText(replay);
	           	 }
        	}catch(Exception ex){
        		
       	    }
       	
        	
        	if(message.getFrom()!=null){
        		from = message.getFrom()[0].toString();
    	        from = from.replace(" ","");
	        	from = from.replace(";","");
	        	from = from.replace(",","");
	        	from = from.replace("``''","");
        	
        	
	   
	        	InternetAddress ia=null;
	        	try{
	        		ia = new InternetAddress(from);	 
	        	}catch(Exception ex){
	        		ia = null;
	        	}
	        	
	        	if(ia==null){
	        		from="发件人不详";
	        	}else{
		        	try{
		            	 if(ia.getPersonal().indexOf("=?x-unknown?") >=0){
		            		 from = ia.getPersonal().replaceAll("x-unknown","gbk" ); 
		            		 from = MimeUtility.decodeText(from);
		            	 }else{
		            		 from = MimeUtility.decodeText(ia.getPersonal());
		            	 }
		        	}catch(Exception ex){
			            if( (ia.getPersonal()!=null)&&(ia.getPersonal().length()!=0) )
			            {
			            	 from = ia.getPersonal();
			            }else{
			            	 from = ia.getAddress();
			            }
		        	}
		        	address = ia.getAddress();
	        	}
        	}else{
        		from="发件人不详";
        	}
        	
       //     if(MimeUtility.decodeText(Util.isoToUtf8(from)).indexOf('?')<0){
         //   	from =Util.isoToGBK(from);
           // }
        	try{
	            if(MimeUtility.decodeText(Util.isoToUtf8(from)).indexOf('?')<0){
	            	from =Util.isoToGBK(from);
	            }
        	}catch(Exception ex){
        		from = "发件人不详";
        	}
    
            String subject = message.getSubject();
            if((subject==null)||(subject.length()==0)){
            	subject="无主题";
            }else if ( subject.indexOf("=?x-unknown?") >=0 ){
            	subject = subject.replaceAll("x-unknown","gbk" ); 
            	subject = MimeUtility.decodeText(subject);
            }else{
            	subject = MimeUtility.decodeText(subject);
            }
            
            if(MimeUtility.decodeText(Util.isoToUtf8(subject)).indexOf('?')<0){
            	subject =Util.isoToGBK(subject);
            }
            String sizeStr = getMessageSize(message);
            Date fromDate = message.getReceivedDate();
            String fromDateS = Util.getFormatDate(fromDate);
            int emailId = message.getMessageNumber(); 
            boolean isSeen = message.isSet(Flags.Flag.SEEN);
         //   String address = ia.getAddress();
         //   String s = "";
            
            
            // -- 得到消息部分(也就是说消息本身)--
            Part messagePart = message;
         //   Object content = messagePart.getContent();
            
            try{
            attachmentNames = this.getAttachMentNames(messagePart);
            }catch(Exception e){
            	
            }
            
            messagePart = textPart(messagePart);
                      
          
            
            // -- 得到类型--
      /*     String contentType = messagePart.getContentType();
    	   String con = "";
            
            // -- 如果内容是plain文本--
            if(contentType.startsWith("text/plain")||(contentType.startsWith("text/html")))
            {
            	try{
            		con = Util.strToHtml(messagePart.getContent().toString());
            	}catch(Exception ex){
            		System.out.print(ex.toString());
            	}
              
            }*/
            
            String contentType = messagePart.getContentType();
        	 ContentType cType = new ContentType(contentType);
      	    String charset=cType.getParameter("charset");

      	  if (charset==null)
      	  	charset = "gb2312";
              
              // -- 如果内容是plain文本,我们可以打印它--
            //  System.out.println("CONTENT:" + contentType);
              String thisLine="";
              String thisContent=new String();
              String thisContentStr=new String();

              if(contentType.startsWith("text/plain")||(contentType.startsWith("text/html")))
              {
   
                  InputStream is = messagePart.getInputStream();
                  BufferedReader reader=null;
                  
                  try{
                      reader = new BufferedReader(new InputStreamReader(is,charset));
                  }catch(Exception ex){
                	  reader = new BufferedReader(new InputStreamReader(is,"gb2312"));
                  }
                  thisLine = reader.readLine();
                  
                  while(thisLine != null)
                  {
                     // System.out.println(thisLine);
                     // thisContent+=(Util.strToHtml(thisLine));
                      thisContent+="<br>"+Util.strToHtml(thisLine);
                      thisContentStr+=Util.strToHtml(thisLine)+"\n";
                      //thisContent+=thisLine.replaceAll("\r\n","<br>"); 
                      thisLine = reader.readLine();
                  }
    
              }

            messageBean.setFrom(from);
            messageBean.setSubject(subject);
            messageBean.setSizeStr(sizeStr);
            messageBean.setFromDate(fromDate);
            messageBean.setEmailId(emailId);
            messageBean.setFromDateS(fromDateS);
            messageBean.setSeen(isSeen);
            messageBean.setMessagePart(messagePart);
            messageBean.setContent(thisContent);
            messageBean.setAttachmentNames(attachmentNames);
            messageBean.setAddress(address);
            messageBean.setContentStr(thisContentStr);
            messageBean.setMessage(message);
            messageBean.setReplay(replay);
 
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return messageBean;
    }
    
    public Part textPart(Part part)
    {
  	Part messagePart=null;
  	Object content;
  	String contentType;

  	messagePart = part;

      try
  	{
  		content = messagePart.getContent();
  		if (content instanceof Multipart)
  		{

  				//System.out.println("getCount()="+((Multipart)content).getCount());
  				for (int i=0;i<((Multipart)content).getCount();i++)
  				{
  					messagePart = ((Multipart)content).getBodyPart(i);
  					content = messagePart.getContent();

  				   if (content instanceof Multipart)
  				//String   disposition   =   ((Multipart)content).getBodyPart(i).getDisposition();
  				// if((disposition!=null)&&((disposition.equals(messagePart.ATTACHMENT))||(disposition.equals(messagePart.INLINE))))
  						textPart(messagePart);
  					else
  					{
  						/*
  						contentType = messagePart.getContentType();
  						//System.out.println("contextType:==="+contentType);
  						if  ( contentType.startsWith("text/plain")|| contentType.startsWith("text/html"))
  						{
  							break;
  						}*/
  						messagePart = text(messagePart);

  					}

  				}
  			}

  	}
  	catch (Exception e)
  	{
  				System.out.println(e);
  		}
     	return messagePart;
    }
    
    
    public Part text(Part part)
    {
  	Part messagePart=null;
  	Object content;
  	String contentType;

  	messagePart = part;
     	return messagePart;
    }
    
    /*
    public String getPart(Part part, int partNum,int x) throws 
       MessagingException,IOException
    {
    String s=""; 
    String s1=""; //x参数来确定是以html格式显示还是以plain
    String s2="";
    String s3="";
    String s5="";
    String sct = part.getContentType();
    if (sct == null) 
    { 
    s="part 无效";
    return s;
    } 
    ContentType ct = new ContentType(sct);

    if (ct.match("text/html")||ct.match("text/plain")) 
    { 
//     display text/plain inline
    s1+=(String)part.getContent(); 
    } 

    if(part.isMimeType("multipart/alternative"))
    { 
    String s6="";
    String s7="";
    Multipart mp = (Multipart)part.getContent();
    int count = mp.getCount();
    for (int i = 0; i < count; i++) 
    { 

    if(mp.getBodyPart(i).isMimeType("text/plain"))
    s7=getPart(mp.getBodyPart(i),i,2);
    if(mp.getBodyPart(i).isMimeType("text/html"))
    s6=getPart(mp.getBodyPart(i), i,1); 
    } 
    if(x==1){s5=s6;} 
    if(x==2){s5=s7;}
    return s5;
    
    }
    
    return s1; 
    }*/

    
    /** 
     * 【得到附件名称】 
     */ 
    public ArrayList getAttachMentNames(Part part)throws Exception{ 
        String fileName = ""; 
        String fullDir ="";
        ArrayList attachmentNames = new ArrayList();
     //   ArrayList fullDirs = 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(); 
                if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){ 
                    fileName = mpart.getFileName(); 
                   // if( (fileName.toLowerCase().indexOf("gb") != -1) ){ 
                      //  fileName = decodeWord(fileName); 
                  //  }
				/*	if (fileName.startsWith("=")){
						fileName = MimeUtility.decodeText(fileName);
					}else{
						fileName = new String(fileName.getBytes("iso-8859-1"),"gb2312");
					}*/
                    
                    if ( fileName.indexOf("=?x-unknown?") >=0 ){
                    	fileName = fileName.replaceAll("x-unknown","gbk" ); // 将编码方式的信息由x-unkown改为gbk
                    
                    	try{
                    		fileName = MimeUtility.decodeText(fileName); //再重新解码
                    	}catch(Exception e1){                              
                    	} 
                    }else{
                    	fileName = MimeUtility.decodeText(fileName);
                    }
                    attachmentNames.add(i+","+fileName);
                   // fullDir = saveFile(fileName,mpart.getInputStream()); 
                } 
      
            } 
        }

        return attachmentNames;
    } 
    
    
    /** 
     * 【真正的保存附件到指定目录里】 
     */ 
    public String saveFile(String fileName,InputStream in)throws Exception{ 
    	
        String osName = System.getProperty("os.name"); 
        String storedir = "";//getAttachPath(); 
        String separator = ""; 
        if(osName == null) osName=""; 
        if(osName.toLowerCase().indexOf("win") != -1){ 
            separator = "\\"; 
            if(storedir == null || storedir.equals("")) storedir="c:\\temp"; 
            
            File file = new File(storedir);

            if(!file.exists()){
	            if (!file.mkdirs()) {
	              throw new IOException("Cannot create directories = " + storedir);
	            }
            }
           file.deleteOnExit();
        }else{ 
            separator = "/"; 
            storedir = "/tmp"; 
        } 

⌨️ 快捷键说明

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