protected void loadChildren() {
    try {
      // connect to the Store if we need to
      if (!store.isConnected()) {
        store.connect();
      }

      // get the default folder, and list the
      // subscribed folders on it
      folder = store.getDefaultFolder();
      // Folder[] sub = folder.listSubscribed();
      Folder[] sub = folder.list();

      // add a FolderTreeNode for each Folder
      int num = sub.length;
      for (int i = 0; i < num; i++) {
        FolderTreeNode node = new FolderTreeNode(sub[i]);
        // we used insert here, since add() would make
        // another recursive call to getChildCount();
        insert(node, i);
      }

    } catch (MessagingException me) {
      me.printStackTrace();
    }
  }
  private static Folder getMailInbox(Store store) {

    Folder folder = null;
    Folder inboxfolder = null;

    try {
      folder = store.getDefaultFolder();
      if (folder == null) throw new Exception("No default folder");
      inboxfolder = folder.getFolder("INBOX");
      if (inboxfolder == null) throw new Exception("No INBOX");
      inboxfolder.open(Folder.READ_ONLY);

      Message[] msgs = inboxfolder.getMessages();

      FetchProfile fp = new FetchProfile();
      fp.add("Subject");
      inboxfolder.fetch(msgs, fp);
      return inboxfolder;

    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
    } catch (MessagingException ex) {
      ex.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {

    }

    return null;
  }
 private void getTopLevelFolders(Store mailBox) throws EmailFetchException {
   try {
     folders.add(mailBox.getDefaultFolder());
   } catch (MessagingException e) {
     throw new EmailFetchException("Folder retreival failed", e);
   }
 }
Exemple #4
0
 public void testGetDefaultFolder() {
   try {
     Folder f = store.getDefaultFolder();
     assertNotNull(f);
   } catch (MessagingException e) {
     fail(e.getMessage());
   }
 }
  @Before
  public void before() throws Exception {
    session = Session.getInstance(new Properties());

    Store localStore = session.getStore("imap");
    localStore.connect("localhost", "camel", "dummy");

    Store riderStore = session.getStore("imap");
    riderStore.connect("camel", "rider", "dummy");

    inbox = localStore.getDefaultFolder();
    inbox.open(Folder.READ_ONLY);
    read = localStore.getFolder("after-processing");
    read.open(Folder.READ_ONLY);

    riderInbox = riderStore.getDefaultFolder();
    riderInbox.open(Folder.READ_ONLY);
  }
 /**
  * Establish connection with mail store and return the configured mail folder.
  *
  * @param mailParms
  * @param mailStore
  * @return the folder specified in configuration
  * @throws MessagingException
  */
 private Folder retrieveMailFolder(final MailTransportParameters mailParms, final Store mailStore)
     throws MessagingException {
   mailStore.connect(
       mailParms.getReadTestHost(),
       mailParms.getReadTestPort(),
       mailParms.getReadTestUserName(),
       mailParms.getReadTestPassword());
   Folder mailFolder = mailStore.getDefaultFolder();
   mailFolder = mailFolder.getFolder(mailParms.getReadTestFolder());
   return mailFolder;
 }
Exemple #7
0
  /**
   * @return all folders, cached
   * @param aStore our mail-store
   * @throws MessagingException if we cannot fetch the folders
   */
  public List<String> getFolders(final Store aStore) throws MessagingException {
    if (myFolders == null) {
      LOG.info("listing folders...");
      JOptionPane.showMessageDialog(
          null,
          "There is no mail-folder configured or it does not exist.\n"
              + "Listing folders after pressing OK...\n"
              + "THIS MAY TAKE A WHILE!");
      myFolders = listFolders(aStore.getDefaultFolder());
    }

    return myFolders;
  }
Exemple #8
0
  // 获得所有邮件的列表
  public Message[] getAllMail() throws Exception {
    // 建立POP3连接
    connect(); // 连接邮件服务器

    // 取得一个Folder对象
    folder = store.getDefaultFolder().getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    // 取得所有的Message对象
    msg = folder.getMessages();
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(msg, profile);
    closeConnect(); // 关闭连接邮件服务器
    return msg;
  }
  /**
   * metoda poveziNaServer povezuje na server, pritom koristi podatke izvucene u konstruktoru te
   * puni Mape s postojecim mapama korisnika
   *
   * @throws NoSuchProviderException
   * @throws MessagingException
   */
  private void poveziNaServer() throws NoSuchProviderException, MessagingException {
    // Start the session
    java.util.Properties properties = System.getProperties();
    session = Session.getInstance(properties, null);

    // Connect to the store
    store = session.getStore("imap");
    store.connect(this.emailPosluzitelj, this.korisnickoIme, this.lozinka);

    folder = store.getDefaultFolder();
    Folder[] folderi = folder.list();

    this.mape = new HashMap<String, String>();
    for (Folder f : folderi) {
      this.mape.put(f.getName(), f.getName());
    }
  }
Exemple #10
0
 // 删除邮件
 public boolean deleteMail(String[] id) {
   boolean isDelete = false;
   try {
     connect(); // 连接邮件服务器
     // 取得一个Folder对象
     folder = store.getDefaultFolder().getFolder("INBOX");
     folder.open(Folder.READ_WRITE);
     Message[] deletemsg = folder.getMessages();
     Message mes = null;
     for (int i = 0; i < id.length; i++) {
       mes = findMail(deletemsg, id[i]); // 查找指定邮件
       mes.setFlag(Flags.Flag.DELETED, true); // 把邮件标记为删除
     }
     closeConnect(); // 关闭邮件服务器的连接并删除邮件
     CheckNewMialUtil.isCheck = true; // 设置新邮件标记
     isDelete = true;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return isDelete;
 }
  protected void createInitialIMAPTestdata(
      final Properties props,
      final String user,
      final String password,
      final int count,
      final boolean deleteall)
      throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

      deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

      if (testroot.exists()) {
        testroot.delete(true);
      }

      final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
      if (testrootenamed.exists()) {
        testrootenamed.delete(true);
      }
    }

    if (!testroot.exists()) {

      testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
      testroot.open(Folder.READ_WRITE);

      testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
      testrootl2.open(Folder.READ_WRITE);
    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
      final MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(EMAIL_TO));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
      message.setSubject(EMAIL_SUBJECT + "::" + i);
      message.setText(EMAIL_TEXT + "::" + SID++);
      message.setSentDate(new Date());
      msgs[i] = message;
    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);
  }
Exemple #12
0
  public static void main(String argv[]) {
    int optind;

    String subject = null;
    String from = null;
    boolean or = false;
    boolean today = false;

    for (optind = 0; optind < argv.length; optind++) {
      if (argv[optind].equals("-T")) {
        protocol = argv[++optind];
      } else if (argv[optind].equals("-H")) {
        host = argv[++optind];
      } else if (argv[optind].equals("-U")) {
        user = argv[++optind];
      } else if (argv[optind].equals("-P")) {
        password = argv[++optind];
      } else if (argv[optind].equals("-or")) {
        or = true;
      } else if (argv[optind].equals("-D")) {
        debug = true;
      } else if (argv[optind].equals("-f")) {
        mbox = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-subject")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-from")) {
        from = argv[++optind];
      } else if (argv[optind].equals("-today")) {
        today = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out.println(
            "Usage: search [-D] [-L url] [-T protocol] [-H host] "
                + "[-U user] [-P password] [-f mailbox] "
                + "[-subject subject] [-from from] [-or] [-today]");
        System.exit(1);
      } else {
        break;
      }
    }

    try {

      if ((subject == null) && (from == null) && !today) {
        System.out.println("Specify either -subject, -from or -today");
        System.exit(1);
      }

      // Get a Properties object
      Properties props = System.getProperties();

      // Get a Session object
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(debug);

      // Get a Store object
      Store store = null;
      if (url != null) {
        URLName urln = new URLName(url);
        store = session.getStore(urln);
        store.connect();
      } else {
        if (protocol != null) store = session.getStore(protocol);
        else store = session.getStore();

        // Connect
        if (host != null || user != null || password != null) store.connect(host, user, password);
        else store.connect();
      }

      // Open the Folder

      Folder folder = store.getDefaultFolder();
      if (folder == null) {
        System.out.println("Cant find default namespace");
        System.exit(1);
      }

      folder = folder.getFolder(mbox);
      if (folder == null) {
        System.out.println("Invalid folder");
        System.exit(1);
      }

      folder.open(Folder.READ_ONLY);
      SearchTerm term = null;

      if (subject != null) term = new SubjectTerm(subject);
      if (from != null) {
        FromStringTerm fromTerm = new FromStringTerm(from);
        if (term != null) {
          if (or) term = new OrTerm(term, fromTerm);
          else term = new AndTerm(term, fromTerm);
        } else term = fromTerm;
      }
      if (today) {
        ReceivedDateTerm dateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
        if (term != null) {
          if (or) term = new OrTerm(term, dateTerm);
          else term = new AndTerm(term, dateTerm);
        } else term = dateTerm;
      }

      Message[] msgs = folder.search(term);
      System.out.println("FOUND " + msgs.length + " MESSAGES");
      if (msgs.length == 0) // no match
      System.exit(1);

      // Use a suitable FetchProfile
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      folder.fetch(msgs, fp);

      for (int i = 0; i < msgs.length; i++) {
        System.out.println("--------------------------");
        System.out.println("MESSAGE #" + (i + 1) + ":");
        dumpPart(msgs[i]);
      }

      folder.close(false);
      store.close();
    } catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
    }

    System.exit(1);
  }
  @Override
  protected Iterator<MultiValueHashMap<String, Object>> getSubDataEntitiesInformation(
      InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
      throws Exception {

    // imap url schema: imap[s]://uname@hostname:port/folder;uidvalidity=385759045/;uid=20. Examples
    // (incl. message-referenzierung)
    // http://xml.resource.org/public/rfc/html/rfc2192.html#anchor10
    // allerdings nimmt der Java ImapStore auch URLs mit Passwörtern an. Dann geht auch
    // imap[s]://uname:pwd@hostname:port/folder;uidvalidity=385759045/;uid=20

    CrawlerContext crawlerContext = context.get(CrawlerContext.class, new CrawlerContext());

    String strContainerURL = metadata.get(Metadata.SOURCE);

    URLName containerURLName = new URLName(strContainerURL);

    if (m_mailStore == null) m_mailStore = connect2Server(containerURLName, context);

    // wenn kein directory angegeben wird, dann crawlen wir einfach den default folder und die inbox
    LinkedList<Folder> llFolderz2Crawl = new LinkedList<Folder>();
    if (containerURLName.getFile() != null) {
      Folder folder = m_mailStore.getFolder(containerURLName.getFile());
      if (folder != null && folder.exists()) llFolderz2Crawl.add(folder);
      else throw new FileNotFoundException("Can't find imap folder '" + folder.getFullName() + "'");

    } else {
      Folder folder = m_mailStore.getDefaultFolder();
      if (folder != null && folder.exists()) llFolderz2Crawl.add(folder);

      folder = m_mailStore.getFolder("INBOX");
      if (folder != null && folder.exists()) llFolderz2Crawl.add(folder);
    }

    LinkedList<MultiValueHashMap<String, Object>> llEntityInfo =
        new LinkedList<MultiValueHashMap<String, Object>>();

    for (Folder folder2crawl : llFolderz2Crawl) {
      // Jetzt haben wir die Containerobjekte - nun geben wir die Daten zu den SubEntities zurück

      // die subfolder
      boolean bFolderCanHaveSubFolders =
          (folder2crawl.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS;

      if (bFolderCanHaveSubFolders) {
        folder2crawl.open(Folder.READ_ONLY);

        Folder[] subFolders = folder2crawl.list();
        for (Folder subFolder : subFolders) {
          URLName urlName = subFolder.getURLName();
          URLName urlNameWithPassword =
              new URLName(
                  containerURLName.getProtocol(),
                  urlName.getHost(),
                  urlName.getPort(),
                  urlName.getFile(),
                  urlName.getUsername(),
                  containerURLName.getPassword());

          if (!checkIfInConstraints(urlName.toString(), null, context)) continue;

          MultiValueHashMap<String, Object> hsEntityInformation =
              new MultiValueHashMap<String, Object>();

          hsEntityInformation.add(CrawlerParser.SOURCEID, urlName);
          hsEntityInformation.add("urlNameWithPassword", urlNameWithPassword);
          hsEntityInformation.add("folder", subFolder.getFullName());

          llEntityInfo.add(hsEntityInformation);
        }
      }

      // die messages
      boolean bFolderCanHaveMessages =
          (folder2crawl.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES;

      if (bFolderCanHaveMessages) {
        if (!folder2crawl.isOpen()) folder2crawl.open(Folder.READ_ONLY);

        // wir holen uns alle nicht-deleted messages, und werfen noch die raus, die 'expunged' sind
        Message[] relevantMessagesOfFolder =
            folder2crawl.search(new FlagTerm(new Flags(Flags.Flag.DELETED), false));
        ArrayList<Message> nonDelNonExpungedMessages = new ArrayList<Message>();
        for (Message message : relevantMessagesOfFolder)
          if (!message.isExpunged()) nonDelNonExpungedMessages.add(message);
        relevantMessagesOfFolder = nonDelNonExpungedMessages.toArray(new Message[0]);

        // die Daten die wir später benötigen holen wir uns effizient in einem Rutsch - deswegen
        // benötigen wir auch keinen Thread mit dem
        // OneAfterOneIterator, um Speicher zu sparen (siehe DirectoryCrawlerParser). Das Array
        // haben wir hier eh. Entweder oder.
        FetchProfile profile = new FetchProfile();
        profile.add(UIDFolder.FetchProfileItem.UID);
        profile.add("Message-ID");
        folder2crawl.fetch(relevantMessagesOfFolder, profile);

        for (int i = 0;
            i < relevantMessagesOfFolder.length && !crawlerContext.stopRequested();
            i++) {
          MimeMessage message = (MimeMessage) relevantMessagesOfFolder[i];

          // hier brauchen wir noch eine URL mit und eine ohne Passwort
          URLName urlName = getMessageUrl(folder2crawl, message);
          URLName urlNameWithPassword =
              new URLName(
                  containerURLName.getProtocol(),
                  urlName.getHost(),
                  urlName.getPort(),
                  urlName.getFile(),
                  urlName.getUsername(),
                  containerURLName.getPassword());

          if (!checkIfInConstraints(urlName.toString(), message, context)) continue;

          MultiValueHashMap<String, Object> hsEntityInformation =
              new MultiValueHashMap<String, Object>();

          hsEntityInformation.add(CrawlerParser.SOURCEID, urlName);
          hsEntityInformation.add("urlNameWithPassword", urlNameWithPassword);
          hsEntityInformation.add("Message-ID", message.getHeader("Message-ID")[0]);
          hsEntityInformation.add("folder", folder2crawl.getFullName());

          llEntityInfo.add(hsEntityInformation);
        }
      }

      // wir haben die folder abgearbeitet, dann können wir diesen Speicher wieder frei geben
      m_hsImapFolder2Stickyness.clear();

      if (folder2crawl.isOpen()) folder2crawl.close(false);
    }

    return llEntityInfo.iterator();
  }
Exemple #14
0
  @Test
  public void pop3() throws Exception {

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "pop3");
    props.setProperty("mail.pop3.host", "pop.163.com");

    Session session = Session.getDefaultInstance(props);
    Store store = session.getStore("pop3");
    store.connect("*****@*****.**", "JShdtyi1234");

    Folder[] folders = store.getDefaultFolder().list(); // store.getPersonalNamespaces();
    for (Folder folder : folders) {
      System.out.println(folder.getName());
    }
    store.close();

    //
    //	        Folder folder = store.getFolder("INBOX");
    //	        folder.open(Folder.READ_WRITE);
    //
    //	        // 全部邮件数
    //	        int messageCount = folder.getMessageCount();
    //	        System.out.println(messageCount);
    //	        Message[] messages = folder.getMessages();
    //	        for (int i = 0; i < messages.length; i++) {
    //	            Message message = messages[i];
    //	            System.out.println(message.getSubject());
    //	            // 删除邮件
    //	            // message.setFlag(Flags.Flag.DELETED, true);
    //	            // 标记为已读
    //	            // message.setFlag(Flags.Flag.SEEN, true);
    //
    //	            //pop3没有判断邮件是否为已读的功能,要使用Imap才可以
    //	            /*Flags flags = message.getFlags();
    //	            if (flags.contains(Flags.Flag.SEEN))
    //	                System.out.println("这是一封已读邮件");
    //	            else {
    //	                System.out.println("未读邮件");
    //	                message.setFlag(Flags.Flag.SEEN, true);
    //	            }*/
    //	            System.out.println("发送时间:" + message.getSentDate());
    //	            System.out.println("主题:" + message.getSubject());
    //	            System.out.println("内容:" + message.getContent());
    //	            //获取所有的Header,头信息
    //	            Enumeration headers = message.getAllHeaders();
    //
    // System.out.println("----------------------allHeaders-----------------------------");
    //	        /*  while (headers.hasMoreElements()) {
    //	                Header header = (Header)headers.nextElement();
    //	                System.out.println(header.getName()+" ======= "+header.getValue());
    //	            }*/
    //
    //	            //解析邮件内容
    //	            Object content = message.getContent();
    //	            if (content instanceof MimeMultipart) {
    //	                MimeMultipart multipart = (MimeMultipart) content;
    //	                parseMultipart(multipart);
    //	            }
    //	            System.out
    //	                    .println("========================================================");
    //	            System.out
    //	                    .println("========================================================");
    //
    //	        }
    //
    //	        folder.close(true);
    //	        store.close();
  }