本帖最后由 lsq1988512 于 2010-08-26 08:53:28 编辑

解决方案 »

  1.   

    public void getMailContent(Part part, boolean flag) throws Exception {   
        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 && flag) {
            bodytext.append((String) part.getContent());
            flag= false;
        } else if (part.isMimeType("text/html") && !conname && flag) {
            bodytext.append((String) part.getContent());
        } 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));
            }
        }
    }你从外面传一个变量进来,判断一下,如果取了"text/plain"就不再取"text/html"不可以吗?
      

  2.   

    根据客户端的设置来做,是html的就读html部分,找不到再读plain部分,否则只取plain部分。
      

  3.   

    你这个getMailContent方法在外面是怎么调用的呀。
    是要循环的吧?
    那你就
    boolean flag = true;
    while(条件) {
    getMailContent(part, flag);
    }就这样不行吗?当读取过"text/plain",flag就被改成false了,再就不会进到"text/html"里面了
      

  4.   

    package com.iss.mail;import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Properties;
    import java.util.Set;import javax.mail.BodyPart;
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Part;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeUtility;public class ProcessReceiveEmail {

    private List<EmailInfo> emailinfoList=new ArrayList<EmailInfo>(); //收件箱的集合
        private String hostName; //主机名
        private String username;  //用户名
        private String password;  //密码
        private Message[] messages ;
        private Store store;
        private Folder folder;
        private StringBuffer  bodytext=new StringBuffer() ;
        private String attachPath="";
        private String date="";
    public Store getStore() {
    return store;
    } public void setStore(Store store) {
    this.store = store;
    } public Folder getFolder() {
    return folder;
    } public void setFolder(Folder folder) {
    this.folder = folder;
    } public Message[] getMessages() {
    return messages;
    } public void setMessages(Message[] messages) {
    this.messages = messages;
    } public String getHostName() {
    return hostName;
    } public void setHostName(String hostName) {
    this.hostName = hostName;
    } public String getUsername() {
    return username;
    } public void setUsername(String username) {
    this.username = username;
    } public String getPassword() {
    return password;
    } public void setPassword(String password) {
    this.password = password;
    }
      
    /**
     * 开始连接
     */
    public void startConnection() throws Exception{    
     Session session = Session.getDefaultInstance(System.getProperties(),
            null);
        Store store = session.getStore("pop3");
        System.out.println("----------start connecting-----------");
        store.connect(hostName, username, password);
        System.out.println("-----------connected successfully---------");
        Folder getFolder=null;
        try
        {
          getFolder = store.getFolder("INBOX");
          getFolder.open(Folder.READ_ONLY);
          System.out.println("-----邮件总数:------"+getFolder.getMessageCount());
          this.setStore(store);
          this.setFolder(getFolder);
          this.setMessages(getFolder.getMessages());
        }    
        catch (MessagingException e)
        {
          e.printStackTrace();
        }
    }


     /**
      * 处理邮件
      * @param part
      * @throws Exception
      */
    public void getMailContent(Part part,boolean flag) throws Exception {  
    String contentType=part.getContentType();
    int nameindex = contentType.indexOf("name");
    boolean conname = false;
    if (nameindex != -1)
    conname = true;
    if (part.isMimeType("text/plain") && !conname&&flag) {
    bodytext.append((String) part.getContent());
       flag=false;
    } else if (part.isMimeType("text/html") && !conname&&flag==false) {
    bodytext.append((String) part.getContent());

    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),flag);
    }


    else if (part.isMimeType("message/rfc822")) {
    getMailContent((Part) part.getContent(),flag);


    else {
    }
    }



     //获得所有的邮件
     public List<EmailInfo> getAllMail() 
      {
     List<EmailInfo> emailinfoList=new ArrayList<EmailInfo>(); //收件箱的集合 emailinfoList=new ArrayList<EmailInfo>(); //收件箱的集合
        int mailArrayLength=this.getMessages().length; 
        Message message=null;
        for (int index = 0; index < mailArrayLength; index++)
        {
        
          try{
         EmailInfo emailinfo=new EmailInfo();
            message =messages[index]; 
            System.out.println("--------读取第"+(index+1)+"邮件-----");
            //System.out.println("contentType:\t"+message.getContentType());
            String contentType=message.getContentType();
            if(contentType.startsWith("text/plain")){
            this.getMailContent(message,true);
            }
            else 
             this.getMailContent(message, false);
            emailinfo.setSubject(MimeUtility.decodeText(message.getSubject())); //标题
            InternetAddress address[] = (InternetAddress[]) message.getFrom();
         emailinfo.setSendAddress(address[0].getAddress()); //发送人邮箱地址
        emailinfo.setSendName(address[0].getPersonal()); //发送人姓名
        emailinfo.setSendDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        .format(message.getSentDate())); //发送日期
        this.date=new SimpleDateFormat("yyyyMMddHHmmss").format(message.getSentDate());
        emailinfo.setEmailContent(this.bodytext.toString());
       
        if(this.isContainAttach(message))//判断该邮件是包含附件
         {
          this.saveAttachMent(message);
         }
         emailinfo.setAttachPath(this.attachPath);
        bodytext=new StringBuffer(""); //让bodytext清空 
        emailinfoList.add(emailinfo);
            
            System.out.println("--------成功读取第"+(index+1)+"邮件-----");
          }
          catch(Exception ex){
          ex.printStackTrace();
          }   
      }
        return emailinfoList;
      }
    /**
     * 关闭连接
     */
     public void closeConnection(){
     try
        {
          messages = null;
          if (folder.isOpen())
            folder.close(true);
          store.close();
          System.out.println("-------------close  success ----------");
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
     } public List<EmailInfo> getEmailinfoList() {
    return emailinfoList;
    } public void setEmailinfoList(List<EmailInfo> emailinfoList) {
    this.emailinfoList = emailinfoList;
    }

       /**
        * 是否包含附件
        * @param part
        * @return
        * @throws Exception
        */
    public boolean isContainAttach(Part part) throws Exception {
    boolean attachflag = false;
    String contentType = part.getContentType();
    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 void saveAttachMent(Part part) throws Exception {
    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 disposition = mpart.getDisposition();
    if ((disposition != null)
    && ((disposition.equals(Part.ATTACHMENT)) || (disposition
    .equals(Part.INLINE)))) {
    fileName = MimeUtility.decodeText(mpart.getFileName());
    if (fileName.toLowerCase().indexOf("gb2312") != -1) {
    fileName = MimeUtility.decodeText(fileName);
    }
    saveFile(fileName, mpart.getInputStream());
    } else if (mpart.isMimeType("multipart/*")) {
    saveAttachMent(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")) {
    saveAttachMent((Part) part.getContent());
    }
    }
    private void saveFile(String fileName, InputStream in) throws Exception {
    String storedir = "E:\\temp\\"+date;
    File storefile = new File(storedir + File.separator + fileName);
     if(!storefile.getParentFile().exists())  //如果文件不存在 
     storefile.getParentFile().mkdirs();  //创建新文件 
    this.attachPath=storefile.getParentFile().getAbsolutePath();  //附件路径指向文件路径
    System.out.println("storefile's path: " + storefile.toString());
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
    bos = new BufferedOutputStream(new FileOutputStream(storefile));
    bis = new BufferedInputStream(in);
    int c;
    while ((c = bis.read()) != -1) {
    bos.write(c);
    bos.flush();
    }
    } catch (Exception exception) {
    exception.printStackTrace();
    throw new Exception("文件保存失败!");
    } finally { bos.close();
    bis.close();
    }
    }


    }