欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java Mail邮件接收工具类

程序员文章站 2024-03-01 17:27:58
下面是一个邮件接收的工具类,有点长!!! public class recivemail { private mimemessage msg = null;...

下面是一个邮件接收的工具类,有点长!!!

public class recivemail { 
 private mimemessage msg = null; 
  private string saveattchpath = ""; 
  private stringbuffer bodytext = new stringbuffer(); 
  private string dateformate = "yy-mm-dd hh:mm"; 
  
  public recivemail(mimemessage msg){ 
    this.msg = msg; 
    } 
  public void setmsg(mimemessage msg) { 
    this.msg = msg; 
  } 
  
  /** 
   * 获取发送邮件者信息 
   * @return 
   * @throws messagingexception 
   */ 
  public string getfrom() throws messagingexception{ 
    internetaddress[] address = (internetaddress[]) msg.getfrom(); 
    string from = address[0].getaddress(); 
    if(from == null){ 
      from = ""; 
    } 
    string personal = address[0].getpersonal(); 
    if(personal == null){ 
      personal = ""; 
    } 
    string fromaddr = personal +"<"+from+">"; 
    return fromaddr; 
  } 
  
  /** 
   * 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址 
   * @param type 
   * @return 
   * @throws messagingexception 
   * @throws unsupportedencodingexception 
   */ 
  public string getmailaddress(string type) throws messagingexception, unsupportedencodingexception{ 
    string mailaddr = ""; 
    string addrtype = type.touppercase(); 
    internetaddress[] address = null; 
    
    if(addrtype.equals("to")||addrtype.equals("cc")||addrtype.equals("bcc")){ 
      if(addrtype.equals("to")){ 
        address = (internetaddress[]) msg.getrecipients(message.recipienttype.to); 
      } 
      if(addrtype.equals("cc")){ 
        address = (internetaddress[]) msg.getrecipients(message.recipienttype.cc); 
      } 
      if(addrtype.equals("bcc")){ 
        address = (internetaddress[]) msg.getrecipients(message.recipienttype.bcc); 
      }    
      if(address != null){ 
        for(int i=0;i<address.length;i++){ 
          string mail = address[i].getaddress(); 
          if(mail == null){ 
            mail = ""; 
          }else{ 
            mail = mimeutility.decodetext(mail); 
          } 
          string personal = address[i].getpersonal(); 
          if(personal == null){ 
            personal = ""; 
          }else{ 
            personal = mimeutility.decodetext(personal); 
          } 
          string compositeto = personal +"<"+mail+">"; 
          mailaddr += ","+compositeto; 
        } 
        mailaddr = mailaddr.substring(1); 
      } 
    }else{ 
      throw new runtimeexception("error email type!"); 
    } 
    return mailaddr; 
  } 
  
  /** 
   * 获取邮件主题 
   * @return 
   * @throws unsupportedencodingexception 
   * @throws messagingexception 
   */ 
  public string getsubject() throws unsupportedencodingexception, messagingexception{ 
    string subject = ""; 
    subject = mimeutility.decodetext(msg.getsubject()); 
    if(subject == null){ 
      subject = ""; 
    } 
    return subject; 
  } 
  
  /** 
   * 获取邮件发送日期 
   * @return 
   * @throws messagingexception 
   */ 
  public string getsenddate() throws messagingexception{ 
    date senddate = msg.getsentdate(); 
    simpledateformat smd = new simpledateformat(dateformate); 
    return smd.format(senddate); 
  } 
  
  /** 
   * 获取邮件正文内容 
   * @return 
   */ 
  public string getbodytext(){ 
    return bodytext.tostring(); 
  } 
  
  /** 
   * 解析邮件,将得到的邮件内容保存到一个stringbuffer对象中, 
   * 解析邮件 主要根据mimetype的不同执行不同的操作,一步一步的解析 
   * @param part 
   * @throws messagingexception 
   * @throws ioexception 
   */ 
  public void getmailcontent(part part) throws messagingexception, ioexception{ 
    
    string contenttype = part.getcontenttype(); 
    int nameindex = contenttype.indexof("name"); 
    boolean conname = false; 
    if(nameindex != -1){ 
      conname = true; 
    } 
    system.out.println("contenttype:"+contenttype); 
    if(part.ismimetype("text/plain")&&!conname){ 
      bodytext.append((string)part.getcontent()); 
    }else if(part.ismimetype("text/html")&&!conname){ 
      bodytext.append((string)part.getcontent()); 
    }else if(part.ismimetype("multipart/*")){ 
      multipart multipart = (multipart) part.getcontent(); 
      int count = multipart.getcount(); 
      for(int i=0;i<count;i++){ 
        getmailcontent(multipart.getbodypart(i)); 
      } 
    }else if(part.ismimetype("message/rfc822")){ 
      getmailcontent((part) part.getcontent()); 
    } 
    
  } 
  
  /** 
   * 判断邮件是否需要回执,如需回执返回true,否则返回false 
   * @return 
   * @throws messagingexception 
   */ 
  public boolean getreplysign() throws messagingexception{ 
    boolean replysign = false; 
    string needreply[] = msg.getheader("disposition-notification-to"); 
    if(needreply != null){ 
      replysign = true; 
    } 
    return replysign; 
  } 
  
  /** 
   * 获取此邮件的message-id 
   * @return 
   * @throws messagingexception 
   */ 
  public string getmessageid() throws messagingexception{ 
    return msg.getmessageid(); 
  } 
  
  /** 
   * 判断此邮件是否已读,如果未读则返回false,已读返回true 
   * @return 
   * @throws messagingexception 
   */ 
  public boolean isnew() throws messagingexception{ 
    boolean isnew = false; 
    flags flags = ((message)msg).getflags(); 
    flags.flag[] flag = flags.getsystemflags(); 
    system.out.println("flags's length:"+flag.length); 
    for(int i=0;i<flag.length;i++){ 
      if(flag[i]==flags.flag.seen){ 
        isnew = true; 
        system.out.println("seen message ......."); 
        break; 
      } 
    } 
    return isnew; 
  } 
  
  /** 
   * 判断是是否包含附件 
   * @param part 
   * @return 
   * @throws messagingexception 
   * @throws ioexception 
   */ 
  public boolean iscontainattch(part part) throws messagingexception, ioexception{ 
    boolean flag = false; 
    
    //string contenttype = part.getcontenttype(); 
    if(part.ismimetype("multipart/*")){ 
      multipart multipart = (multipart) part.getcontent(); 
      int count = multipart.getcount(); 
      for(int i=0;i<count;i++){ 
        bodypart bodypart = multipart.getbodypart(i); 
        string dispostion = bodypart.getdisposition(); 
        if((dispostion != null)&&(dispostion.equals(part.attachment)||dispostion.equals(part.inline))){ 
          flag = true; 
        }else if(bodypart.ismimetype("multipart/*")){ 
          flag = iscontainattch(bodypart); 
        }else{ 
          string contype = bodypart.getcontenttype(); 
          if(contype.tolowercase().indexof("appliaction")!=-1){ 
            flag = true; 
          } 
          if(contype.tolowercase().indexof("name")!=-1){ 
            flag = true; 
          } 
        } 
      } 
    }else if(part.ismimetype("message/rfc822")){ 
      flag = iscontainattch((part) part.getcontent()); 
    } 
    
    return flag; 
  } 
  
  /** 
   * 保存附件 
   * @param part 
   * @throws messagingexception 
   * @throws ioexception 
   */ 
  public void saveattchment(part part) throws messagingexception, ioexception{ 
    string filename = ""; 
    if(part.ismimetype("multipart/*")){ 
      multipart mp = (multipart) part.getcontent(); 
      for(int i=0;i<mp.getcount();i++){ 
        bodypart mpart = mp.getbodypart(i); 
        string dispostion = mpart.getdisposition(); 
        if((dispostion != null)&&(dispostion.equals(part.attachment)||dispostion.equals(part.inline))){ 
          filename = mpart.getfilename(); 
          if(filename.tolowercase().indexof("gb2312")!=-1){ 
            filename = mimeutility.decodetext(filename); 
          } 
          savefile(filename,mpart.getinputstream()); 
        }else if(mpart.ismimetype("multipart/*")){ 
          saveattchment(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")){ 
      saveattchment((part) part.getcontent()); 
    } 
  } 
  /** 
   * 获得保存附件的地址 
   * @return 
   */ 
  public string getsaveattchpath() { 
    return saveattchpath; 
  } 
  /** 
   * 设置保存附件地址 
   * @param saveattchpath 
   */ 
  public void setsaveattchpath(string saveattchpath) { 
    this.saveattchpath = saveattchpath; 
  } 
  /** 
   * 设置日期格式 
   * @param dateformate 
   */ 
  public void setdateformate(string dateformate) { 
    this.dateformate = dateformate; 
  } 
  /** 
   * 保存文件内容 
   * @param filename 
   * @param inputstream 
   * @throws ioexception 
   */ 
  private void savefile(string filename, inputstream inputstream) throws ioexception { 
    string osname = system.getproperty("os.name"); 
    string storedir = getsaveattchpath(); 
    string sepatror = ""; 
    if(osname == null){ 
      osname = ""; 
    } 
    
    if(osname.tolowercase().indexof("win")!=-1){ 
      sepatror = "//"; 
      if(storedir==null||"".equals(storedir)){ 
        storedir = "d://temp"; 
      } 
    }else{ 
      sepatror = "/"; 
      storedir = "/temp"; 
    } 
    
    file storefile = new file(storedir+sepatror+filename); 
    system.out.println("storefile's path:"+storefile.tostring()); 
    
    bufferedoutputstream bos = null; 
    bufferedinputstream bis = null; 
    
    try { 
      bos = new bufferedoutputstream(new fileoutputstream(storefile)); 
      bis = new bufferedinputstream(inputstream); 
      int c; 
      while((c= bis.read())!=-1){ 
        bos.write(c); 
        bos.flush(); 
      } 
    } catch (filenotfoundexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      // todo auto-generated catch block 
      e.printstacktrace(); 
    }finally{ 
      bos.close(); 
      bis.close(); 
    } 
    
  } 
  
  public void recive(part part,int i) throws messagingexception, ioexception{ 
    system.out.println("------------------start-----------------------"); 
    system.out.println("message"+i+" subject:" + getsubject()); 
    system.out.println("message"+i+" from:" + getfrom()); 
    system.out.println("message"+i+" isnew:" + isnew()); 
    boolean flag = iscontainattch(part); 
    system.out.println("message"+i+" iscontainattch:" +flag); 
    system.out.println("message"+i+" replysign:" + getreplysign()); 
    getmailcontent(part); 
    system.out.println("message"+i+" content:" + getbodytext()); 
    setsaveattchpath("c://temp//"+i); 
    if(flag){ 
      saveattchment(part); 
    } 
    system.out.println("------------------end-----------------------"); 
  }

}

邮件接收与工具类的使用,有好几种邮件接收的写法!:

看了很多网上其他代码,pop3server的值是pop.mail.163.com,但是试了试不成功,还有 user的值既可以是带有 也可以是username。

如果收件邮箱是163邮箱,必须先登陆163邮箱中设置,开启pop3服务。至于别的邮箱暂不知道。

public static void main(string[] args) throws exception { 
    // 连接pop3服务器的主机名、协议、用户名、密码 
    string pop3server = "pop.163.com"; 
    string protocol = "pop3"; 
    string user = "username"; 
    string pwd = "password"; 
     
    // 创建一个有具体连接信息的properties对象 
    properties props = new properties(); 
    props.setproperty("mail.store.protocol", protocol); 
    props.setproperty("mail.pop3.host", pop3server); 
     
    // 使用properties对象获得session对象 
    session session = session.getinstance(props); 
    session.setdebug(true); 
     
    // 利用session对象获得store对象,并连接pop3服务器 
    store store = session.getstore(); 
    store.connect(pop3server, user, pwd); 
     
    // 获得邮箱内的邮件夹folder对象,以"只读"打开 
    folder folder = store.getfolder("inbox"); 
    folder.open(folder.read_only); 
     
    // 获得邮件夹folder内的所有邮件message对象 
    message [] messages = folder.getmessages();  
    recivemail rm = null; 
    for(int i=0;i< messages.size() ;i++){ 
      rm = new recivemail((mimemessage) messages[i]); 
      rm.recive(messages[i],i);; 
    } 
     folder.close(false); 
    store.close(); 
}