Exemplo n.º 1
0
 public void flagAsDeleted(int[] messageIds) throws Exception {
   Folder fold = null;
   try {
     fold = getFolder();
     if (messageIds != null && messageIds.length > 0) {
       for (int i = 0; i < messageIds.length; i++) {
         try {
           if (messageIds[i] > 0) {
             Message msg = fold.getMessage(messageIds[i]);
             msg.setFlag(Flags.Flag.SEEN, true);
             msg.setFlag(Flags.Flag.DELETED, true);
           }
         } catch (Exception e) {
           log.debug("error while deleting messsage", e);
         }
       }
     }
   } catch (MessagingException e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } catch (IndexOutOfBoundsException e) {
     log.warn("Maybe you are double clicking the delete button. do it a little bit slowly :) ", e);
   } catch (Exception e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   }
 }
Exemplo n.º 2
0
  /**
   * @param messageIds
   * @param destFolders
   * @throws Exception
   */
  public void moveEmails(int messageIds[], String destFolders[]) throws Exception {
    ProtocolFactory factory = new ProtocolFactory(profile, auth, handler);
    ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory.getImap(folder);
    Folder from = fromProtocol.getFolder();
    Folder dest = null;

    try {
      Message msg = null;
      // copy messages to destination folder first
      for (int i = 0; i < messageIds.length; i++) {
        try {
          msg = fromProtocol.getMessage(messageIds[i]);
          ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory.getImap(destFolders[i]);
          dest = destProtocol.getFolder();
          from.copyMessages(new Message[] {msg}, dest);
        } catch (Exception e) {
          log.debug("error while copying messages", e);
        }
      }

      // now delete the processed messages all at a time.
      // deleteMessages(messageIds);
      flagAsDeleted(messageIds);

    } catch (Exception e) {
      log.warn("Moving message failed.", e);
    }
  }
Exemplo n.º 3
0
 /** @param newName */
 public void renameFolder(String newName) throws Exception {
   Folder fOld = getFolder();
   Folder fNew = handler.getStore().getFolder(profile.getFolderNameSpace() + newName);
   closeFolder(fOld);
   fOld.renameTo(fNew);
   fNew.setSubscribed(true);
 }
Exemplo n.º 4
0
  /**
   * @param msgId
   * @param destFolder
   * @throws Exception
   */
  public void moveEmail(Long msgId, String destFolder) throws Exception {
    ProtocolFactory factory = new ProtocolFactory(profile, auth, handler);
    ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory.getImap(folder);
    ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory.getImap(destFolder);
    Folder from = fromProtocol.getFolder();
    Folder dest = null;

    try {
      Message msg = fromProtocol.getMessage(msgId.intValue());
      if (msg != null) {
        // because of the buggy imap servers lost the connection after getMessage
        // we need to check if the folder is open or not.
        // (Do not use uw-imapd, it sucks!!!)
        from = fromProtocol.getFolder();
        dest = destProtocol.getFolder();
        from.copyMessages(new Message[] {msg}, dest);
        // deleteMessages(new int[] {msg.getMessageNumber()});
        flagAsDeleted(new int[] {msg.getMessageNumber()});
      }
    } catch (IndexOutOfBoundsException e) {
      log.debug("Index kaçtı. Moving message to folder : " + destFolder + " failed.", e);
    } catch (Exception e) {
      log.warn("Moving message to folder : " + destFolder + " failed.", e);
    }
  }
  @Test
  public void shouldReceiveMessageAndSendOutgoingMail() throws Exception {
    // send test message to camel@localhost
    MimeMessage msg = new MimeMessage(session);
    msg.setSubject(SUBJECT);
    msg.setRecipients(RecipientType.TO, "camel@localhost");
    msg.setText(PAYLOAD);

    Transport.send(msg);
    Thread.sleep(500);

    Message[] messages = inbox.getMessages();
    // verify mailbox states, note that mock javamail do not create new
    // folders, so everything goes to same place
    assertEquals(2, messages.length);

    messages = read.getMessages();
    assertEquals(2, messages.length);
    assertEquals(PAYLOAD, messages[0].getContent());
    assertEquals(SUBJECT, messages[0].getSubject());

    messages = riderInbox.getMessages();
    assertEquals(1, messages.length);
    assertEquals("Forwarded message", messages[0].getSubject());
    assertEquals(PAYLOAD, messages[0].getContent());
  }
Exemplo n.º 6
0
 /* (non-Javadoc)
  * @see org.claros.commons.mail.protocols.Protocol#deleteMessages(int[])
  */
 public ConnectionMetaHandler deleteMessages(int[] messageIds)
     throws MailboxActionException, SystemException, ConnectionException {
   Folder fold = null;
   try {
     fold = getFolder();
     if (messageIds != null && messageIds.length > 0) {
       for (int i = 0; i < messageIds.length; i++) {
         try {
           if (messageIds[i] > 0) {
             Message msg = fold.getMessage(messageIds[i]);
             msg.setFlag(Flags.Flag.DELETED, true);
           }
         } catch (Exception e) {
           log.debug("error while deleting messsage", e);
         }
       }
       fold.expunge();
     }
   } catch (MessagingException e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } catch (IndexOutOfBoundsException e) {
     log.error("Maybe you are double clicking the delete button", e);
   } catch (Exception e) {
     log.error("Could not delete message ids: " + messageIds, e);
     throw new MailboxActionException(e);
   } finally {
     closeFolder(fold);
     //			disconnect();
   }
   return handler;
 }
Exemplo n.º 7
0
  /**
   * Endpoint can be in the form of pop3://username:[email protected]
   *
   * @param endpointUri
   * @param timeout
   * @return
   * @throws Exception
   */
  public UMOMessage receive(UMOEndpointURI endpointUri, long timeout) throws Exception {
    initialise(endpointUri);

    long t0 = System.currentTimeMillis();
    if (timeout < 0) {
      timeout = Long.MAX_VALUE;
    }
    do {
      int count = folder.getMessageCount();
      if (count > 0) {
        Message message = folder.getMessage(1);
        // so we don't get the same message again
        message.setFlag(Flags.Flag.DELETED, true);
        return new MuleMessage(connector.getMessageAdapter(message));
      } else if (count == -1) {
        throw new MessagingException(
            "Cannot monitor folder: " + folder.getFullName() + " as folder is closed");
      }
      long sleep =
          Math.min(this.connector.getCheckFrequency(), timeout - (System.currentTimeMillis() - t0));
      if (sleep > 0) {
        if (logger.isDebugEnabled()) {
          logger.debug("No results, sleeping for " + sleep);
        }
        Thread.sleep(sleep);
      } else {
        logger.debug("Timeout");
        return null;
      }
    } while (true);
  }
Exemplo n.º 8
0
  /** добавить сообщение в папку "отправленные" */
  private void appendEmailToSent(Message message) {
    try {
      Properties properties = new Properties();

      properties.put("mail.store.protocol", "imaps");
      MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
      socketFactory.setTrustAllHosts(true);
      properties.put("mail.imaps.ssl.socketFactory", socketFactory);
      properties.put("mail.imaps.ssl.trust", "*");
      properties.put("mail.imaps.ssl.checkserveridentity", "false");
      properties.put("mail.imaps.host", HOST);
      properties.put("mail.imaps.port", IMAP_PORT);
      // присоединиться к IMAP
      Session session = Session.getDefaultInstance(properties, null);
      Store store = session.getStore("imaps");
      store.connect(HOST, IMAP_PORT, POST_LOGIN, POST_PASSWORD);
      // добавить сообщение в папку
      Folder inbox = store.getFolder("Sent");
      inbox.open(Folder.READ_WRITE);
      Message[] msgs = {message};
      inbox.appendMessages(msgs);
      inbox.close(false);
      store.close();
    } catch (Exception e) {
      getActionResult().addMessage("не удалось поместить письмо в папку отправленные");
    }
  }
  /**
   * metoda preuzmiPoruke preuzima poruke iz odabrane mape i puni listu poruka
   *
   * @throws MessagingException
   * @throws IOException
   */
  private void preuzmiPoruke() throws MessagingException, IOException {
    Message[] messages;

    // Open the INBOX folder
    folder = store.getFolder(this.odabranaMapa);
    folder.open(Folder.READ_ONLY);

    messages = folder.getMessages();

    this.poruke = new ArrayList<Poruka>();

    for (int i = 0; i < messages.length; ++i) {
      Message m = messages[i];
      Poruka p =
          new Poruka(
              m.getHeader("Message-ID")[0],
              m.getSentDate(),
              m.getFrom()[0].toString(),
              m.getSubject(),
              m.getContentType(),
              m.getSize(),
              0,
              m.getFlags(),
              null,
              true,
              true,
              m.getContent().toString());
      // TODO potraziti broj privitaka, sad je hardkodirano da ih je 0

      this.poruke.add(p);
    }
  }
Exemplo n.º 10
0
  public static Folder getFolder(Folder store, String name, boolean autoCreate) {
    int sepIdx = name.indexOf('/');
    if (sepIdx > 0) {
      String firstName = name.substring(0, sepIdx);
      String lastName = name.substring(sepIdx + 1);
      Folder parent = getFolder(store, firstName, autoCreate);
      if (parent == null) return null;
      return getFolder(parent, lastName, autoCreate);
    }

    Folder folder;
    try {
      folder = store.getFolder(name);
    } catch (MessagingException ex) {
      throw new RuntimeException("Getting folder failed: " + name, ex);
    }
    boolean folderExists;
    try {
      folderExists = folder.exists();
    } catch (MessagingException ex) {
      throw new RuntimeException("Querying folder for existence failed: " + name, ex);
    }
    if (!folderExists) {
      if (!autoCreate) return null;
      boolean created;
      try {
        created = folder.create(Folder.HOLDS_MESSAGES);
      } catch (MessagingException ex) {
        throw new RuntimeException("Creating folder failed: " + name, ex);
      }
      if (!created) throw new RuntimeException("Creating folder failed: " + name);
      LOG.info("Mailbox folder created:", name);
    }
    return folder;
  }
Exemplo n.º 11
0
  /**
   * @param aWritableModel
   * @param store
   * @return
   * @throws MessagingException
   * @throws JAXBException
   */
  private Folder getInputFolder(final GnucashWritableFile aWritableModel, Store store)
      throws MessagingException, JAXBException {
    String folderName = aWritableModel.getUserDefinedAttribute("imap.folder");
    Folder folder = null;
    if (folderName != null) {
      folder = store.getFolder(folderName);
    }
    while (folder == null || !folder.exists()) {
      final JDialog selectFolderDialog = new JDialog((JFrame) null, "Select mail folder");
      selectFolderDialog.getContentPane().setLayout(new BorderLayout());
      final JList folderListBox = new JList(new Vector<String>(getFolders(store)));
      JButton okButton = new JButton("OK");
      okButton.addActionListener(
          new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent aE) {
              if (folderListBox.getSelectedIndices() != null) {
                if (folderListBox.getSelectedIndices().length == 1) {
                  selectFolderDialog.setVisible(false);
                }
              }
            }
          });
      selectFolderDialog.getContentPane().add(new JScrollPane(folderListBox), BorderLayout.CENTER);
      selectFolderDialog.getContentPane().add(okButton, BorderLayout.SOUTH);
      selectFolderDialog.setModal(true);
      selectFolderDialog.pack();
      selectFolderDialog.setVisible(true);
      folderName = folderListBox.getSelectedValue().toString();
      aWritableModel.setUserDefinedAttribute("imap.folder", folderName);
      folder = store.getFolder(folderName);
    }
    return folder;
  }
Exemplo n.º 12
0
  /**
   * Retrieves headers of new messages.
   *
   * @return a string array containing the message headers
   */
  public String[] getNewMessageHeaders() throws Exception {
    logger.info("[Inbound:MailServerFolder] Calling getNewMessageHeaders");
    reopen(); // Make sure the folder is open

    //
    // Deliver only new messages to the MDB
    //

    try {
      if (folder.hasNewMessages()) {
        int newMsgs = folder.getNewMessageCount();
        int msgCount = folder.getMessageCount();
        Message[] msgs = folder.getMessages(msgCount - newMsgs + 1, msgCount);
        String[] headers = new String[msgs.length];
        logger.log(Level.INFO, "messages length: {0}", msgs.length);
        logger.log(Level.INFO, "headers length: {0}", headers.length);
        for (int i = 0; i < headers.length; i++) {
          logger.log(
              Level.INFO,
              "[Inbound:MailServerFolder] Packing message with SUBJECT: {0}",
              msgs[i].getSubject());
          headers[i] = msgs[i].getSubject();
        }
        return headers;
      }
    } catch (Exception e) {
      logger.severe("[Inbound:MailServerFolder] Exception obtaining messages from mail server:");
    }
    return null;
  }
  @Override
  protected void doDisconnect() throws Exception {
    // close and expunge deleted messages
    try {
      if (folder != null) {
        try {
          folder.expunge();
        } catch (MessagingException e) {
          if (logger.isDebugEnabled()) {
            logger.debug("ignoring exception on expunge: " + e.getMessage());
          }
        }
        if (folder.isOpen()) {
          folder.close(true);
        }
      }
    } catch (Exception e) {
      logger.error("Failed to close inbox: " + e.getMessage(), e);
    }

    try {
      if (moveToFolder != null) {
        if (moveToFolder.isOpen()) {
          moveToFolder.close(false);
        }
      }
    } catch (Exception e) {
      logger.error("Failed to close moveToFolder: " + e.getMessage(), e);
    }
  }
 public MessagesWrapper search(List<SearchTerm> term) throws MessagingException {
   if (!folder.isOpen()) {
     folder.open(Folder.READ_ONLY);
   }
   Message[] messages = folder.search(and(term));
   return new MessagesWrapper(logger, Arrays.asList(messages), folder);
 }
Exemplo n.º 15
0
  public static int removeEmails(Account account, String protocol)
      throws MessagingException, UnknownHostException {
    int count = 0;
    Session session =
        Session.getInstance(
            Protocol.POP3.equals(protocol)
                ? getPop3MailProperties(account)
                : getImapMailProperties(account));
    Folder inbox;

    //        store = session.getStore("imap");
    if (account.getLoginName().contains("@yahoo.")) {
      IMAPStore imapstore = (IMAPStore) session.getStore(protocol);
      yahooConnect(account, imapstore, true);
      inbox = imapstore.getFolder("INBOX");
    } else {
      Store store = session.getStore(protocol);
      store.connect(account.getReceiveHost(), account.getLoginName(), account.getPassword());
      inbox = store.getFolder("INBOX");
    }

    inbox.open(Folder.READ_WRITE);

    count = inbox.getMessageCount();
    for (Message message : inbox.getMessages()) {
      message.setFlag(Flags.Flag.DELETED, true);
    }
    inbox.close(true);
    return count;
  }
Exemplo n.º 16
0
 /** @return */
 public int getTotalMessageCount() throws Exception {
   Folder f = getFolder();
   if (f.exists()) {
     return f.getMessageCount();
   }
   return 0;
 }
Exemplo n.º 17
0
  public void setFolder(Folder newFolder) throws MessagingException {
    if (folder != null) {
      try {
        folder.removeMessageCountListener(messageCountListener);
        folder.close(true);
      } catch (Exception ex) {
        // Failure here seems to happen relatively often.
        // enp has a corrupt folder, for example, and enh finds that Exchange seems to sometimes
        // close folders on him, maybe because he's running Outlook at the same time.
        // It's not currently obvious that there's much to be gained by showing this error to the
        // user.
        // It does seem that we should blunder on, rather than back out, because the UI's already
        // been updated by this point.
        // If we back out here, we really need to back out the UI change too, and going that route
        // seems like a mistake.
        ex.printStackTrace();
      }
    }

    this.folder = newFolder;
    this.messages = Collections.<Message>emptyList();

    if (folder != null) {
      scanWholeFolder();
      folder.addMessageChangedListener(messageChangedListener);
      folder.addMessageCountListener(messageCountListener);
    }
  }
  /**
   * Make a specific request to the underlying transport. Endpoint can be in the form of
   * pop3://username:[email protected]
   *
   * @param timeout the maximum time the operation should block before returning. The call should
   *     return immediately if there is data available. If no data becomes available before the
   *     timeout elapses, null will be returned
   * @return the result of the request wrapped in a MuleMessage object. Null will be returned if no
   *     data was avaialable
   * @throws Exception if the call to the underlying protocal causes an exception
   */
  @Override
  protected MuleMessage doRequest(long timeout) throws Exception {
    long t0 = System.currentTimeMillis();
    if (timeout < 0) {
      timeout = Long.MAX_VALUE;
    }

    do {
      if (hasMessages()) {
        int count = getMessageCount();
        if (count > 0) {
          Message message = getNextMessage();
          if (message != null) {
            // so we don't get the same message again
            flagMessage(message);

            if (moveToFolder != null) {
              Message newMessage = message;
              // If we're using IMAP we need to cache the message contents so the message is
              // accessible after the
              // folder is closed
              if (message instanceof IMAPMessage) {
                // We need to copy and cache so that the message cna be moved
                newMessage = new MimeMessage((IMAPMessage) message);
              }
              folder.copyMessages(new Message[] {message}, moveToFolder);
              message = newMessage;
            }
            return createMuleMessage(message, endpoint.getEncoding());
          }
        } else if (count == -1) {
          throw new MessagingException(
              "Cannot monitor folder: " + folder.getFullName() + " as folder is closed");
        }
      }

      long sleep =
          Math.min(
              castConnector().getCheckFrequency(), timeout - (System.currentTimeMillis() - t0));

      if (sleep > 0) {
        if (logger.isDebugEnabled()) {
          logger.debug("No results, sleeping for " + sleep);
        }
        try {
          Thread.sleep(sleep);
        } catch (InterruptedException e) {
          logger.warn(
              "Thread interrupted while requesting email on: "
                  + endpoint.getEndpointURI().toString());
          return null;
        }
      } else {

        logger.debug("Timeout");
        return null;
      }

    } while (true);
  }
Exemplo n.º 19
0
  public void p(Object obj) throws Exception {
    Object[] o = (Object[]) obj;
    if (o.length != 3) throw new Exception("Wrong data number: " + o.length);

    File dir = (File) o[0];
    Object progress = o[1];
    Set interrupt = (Set) o[2];

    String[] infos = (String[]) askInfos.g();
    if (infos == null) return;

    Folder folder = (Folder) buildInbox.t(infos);
    folder.open(Folder.READ_ONLY);

    Message[] messages = folder.getMessages();

    int size = messages.length;
    if (progress != null) ((V) progress).v("size", "" + size);

    for (int i = 0; i < size; i++) {
      String timeStamp = (String) messageToTimeStamp.t(messages[i]);
      writeEml.p(new Object[] {dir, timeStamp, messages[i]});

      if (progress != null) ((E) progress).e();
      if (interrupt != null && !interrupt.isEmpty()) break;
    }

    folder.close(false);
  }
Exemplo n.º 20
0
  public void testSearch() throws Exception {

    Store store = session.getStore("imap");

    store.connect("mail.skyteam.prv", "advalso", "");

    Folder folder = store.getFolder("Shitty Things");

    System.out.println("got folder: " + folder);

    folder.open(Folder.READ_ONLY);

    SearchTerm term = new FromStringTerm("steve");

    Message message[] = folder.search(term);

    System.out.println("there are " + message.length + " matching shitty messages.");

    for (Message msg : message) {
      System.out.println(((MimeMessage) msg).getContent());
    }

    folder.close(false);
    store.close();
  }
Exemplo n.º 21
0
  /**
   * @return
   * @throws Exception
   */
  public synchronized Folder getFolder() throws Exception {
    String folder = Constants.FOLDER_INBOX(profile);

    Folder fold = (Folder) pop3Folders.get(auth.getUsername());
    if (fold != null && fold.isOpen()) {
      return fold;
    } else {
      if (folder != null && handler != null) {
        Store store = handler.getStore();
        if (store == null || !store.isConnected()) {
          System.out.println("Connection is closed. Restoring it...");
          handler = connect(Constants.CONNECTION_READ_WRITE);
          System.out.println("Connection re-established");
        }
        fold = handler.getStore().getFolder(folder);
        if (!fold.isOpen()) {
          System.out.println("Folder :" + folder + " is closed. Opening again.");
          fold.open(Constants.CONNECTION_READ_WRITE);
          System.out.println("Folder is open again.");

          pop3Folders.put(auth.getUsername(), fold);
        }
      }
    }
    return fold;
  }
Exemplo n.º 22
0
  /**
   * Fetches and returns message headers as message objects.
   *
   * @return
   * @throws SystemException
   * @throws ConnectionException
   */
  public ArrayList fetchAllHeadersAsMessages() throws SystemException, ConnectionException {
    ArrayList headers = null;
    Folder fold = null;
    try {
      fold = getFolder();
      closeFolder(fold);
      fold = getFolder();
      headers = new ArrayList();

      Message[] msgs = fold.getMessages();
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      fp.add(FetchProfile.Item.FLAGS);
      fp.add(FetchProfile.Item.CONTENT_INFO);
      fp.add("Size");
      fp.add("Date");
      fold.fetch(msgs, fp);

      Message msg = null;
      for (int i = 0; i < msgs.length; i++) {
        msg = msgs[i];
        headers.add(msg);
      }
    } catch (Exception e) {
      System.out.println("Could not fetch message headers. Is mbox connection still alive???");
      throw new ConnectionException(e);
    }
    return headers;
  }
Exemplo n.º 23
0
 /**
  * @param msgId
  * @throws Exception
  */
 public void markAsRead(Long msgId) throws Exception {
   Folder f = getFolder();
   try {
     Message msg = f.getMessage(msgId.intValue());
     msg.setFlag(Flags.Flag.SEEN, true);
   } catch (MessagingException e) {
     log.warn("Marking as Read not worked.", e);
   }
 }
Exemplo n.º 24
0
  /**
   * Fetches all e-mail headers from the server, with appropriate fields already set.
   *
   * @param handler
   * @return ArrayList of MessageHeaders
   * @throws ConnectionException
   */
  public ArrayList fetchAllHeaders() throws SystemException, ConnectionException {
    ArrayList headers = null;
    Folder fold = null;
    try {
      fold = getFolder();
      closeFolder(fold);
      fold = getFolder();

      headers = new ArrayList();
      EmailHeader header = null;

      Message[] msgs = fold.getMessages();
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      fp.add(FetchProfile.Item.FLAGS);
      fp.add(FetchProfile.Item.CONTENT_INFO);
      fp.add("Size");
      fp.add("Date");
      fold.fetch(msgs, fp);

      Message msg = null;
      for (int i = 0; i < msgs.length; i++) {
        try {
          header = new EmailHeader();
          msg = msgs[i];

          header.setMultipart((msg.isMimeType("multipart/*")) ? true : false);
          header.setMessageId(i + 1);
          header.setFrom(msg.getFrom());
          header.setTo(msg.getRecipients(Message.RecipientType.TO));
          header.setCc(msg.getRecipients(Message.RecipientType.CC));
          header.setBcc(msg.getRecipients(Message.RecipientType.BCC));
          header.setDate(msg.getSentDate());
          header.setReplyTo(msg.getReplyTo());
          header.setSize(msg.getSize());
          header.setSubject(msg.getSubject());

          // now set the human readables.
          header.setDateShown(Formatter.formatDate(header.getDate(), "dd.MM.yyyy HH:mm"));
          header.setFromShown(Utility.addressArrToString(header.getFrom()));
          header.setToShown(Utility.addressArrToString(header.getTo()));
          header.setCcShown(Utility.addressArrToString(header.getCc()));
          header.setSizeShown(Utility.sizeToHumanReadable(header.getSize()));

          // it is time to add it to the arraylist
          headers.add(header);
        } catch (MessagingException e1) {
          System.out.println(
              "Could not parse headers of e-mail. Message might be defuncted or illegal formatted.");
        }
      }
    } catch (Exception e) {
      System.out.println("Could not fetch message headers. Is mbox connection still alive???");
      throw new ConnectionException(e);
    }
    return headers;
  }
Exemplo n.º 25
0
 public static void closeFolder(Folder folder, boolean delete) {
   if (folder == null) return;
   if (!folder.isOpen()) return;
   try {
     folder.close(delete);
   } catch (Exception ex) {
     if (delete) throw new RuntimeException(ex);
   }
 }
Exemplo n.º 26
0
  @Override
  public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
      Pair<String, String> credentials =
          GuiUtils.askCredentials(
              ConfigFetch.getSuperParentFrame(),
              "Enter Gmail Credentials",
              getGmailUsername(),
              getGmailPassword());
      if (credentials == null) return null;
      setGmailUsername(credentials.first());
      setGmailPassword(credentials.second());
      PluginUtils.saveProperties("conf/rockblock.props", this);
      askGmailPassword = false;
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
      Session session = Session.getDefaultInstance(props, null);
      Store store = session.getStore("imaps");
      store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

      Folder inbox = store.getFolder("Inbox");
      inbox.open(Folder.READ_ONLY);
      int numMsgs = inbox.getMessageCount();

      for (int i = numMsgs; i > 0; i--) {
        Message m = inbox.getMessage(i);
        if (m.getReceivedDate().before(timeSince)) {
          break;
        } else {
          MimeMultipart mime = (MimeMultipart) m.getContent();
          for (int j = 0; j < mime.getCount(); j++) {
            BodyPart p = mime.getBodyPart(j);
            Matcher matcher = pattern.matcher(p.getContentType());
            if (matcher.matches()) {
              InputStream stream = (InputStream) p.getContent();
              byte[] data = IOUtils.toByteArray(stream);
              IridiumMessage msg = process(data, matcher.group(1));
              if (msg != null) messages.add(msg);
            }
          }
        }
      }
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
      System.exit(1);
    } catch (MessagingException ex) {
      ex.printStackTrace();
      System.exit(2);
    }

    return messages;
  }
Exemplo n.º 27
0
 /**
  * Log the name of a folder and it´s subfolders.
  *
  * @param aFolder the folder to show
  * @throws MessagingException if we cannot list the subfolders
  * @return a newline separated list of all folders
  */
 private List<String> listFolders(final Folder aFolder) throws MessagingException {
   List<String> retval = new LinkedList<String>();
   retval.add(aFolder.getFullName());
   LOG.info("folder: " + aFolder.getFullName());
   Folder[] subfolders = aFolder.list();
   for (Folder folder : subfolders) {
     retval.addAll(listFolders(folder));
   }
   return retval;
 }
Exemplo n.º 28
0
 public static void copyMessage(Message message, Folder destination) {
   boolean sourceOpened = false;
   boolean destinationOpened = false;
   Folder source = message.getFolder();
   try {
     if (!source.isOpen()) {
       source.open(Folder.READ_ONLY);
       sourceOpened = true;
     }
     if (!destination.isOpen()) {
       destination.open(Folder.READ_WRITE);
       destinationOpened = true;
     }
     try {
       source.copyMessages(new Message[] {message}, destination);
     } catch (MessagingException e) {
       destination.appendMessages(new Message[] {message});
     }
   } catch (MessagingException ex) {
     throw new RuntimeException(
         "Copying message "
             + toString(message)
             + " from "
             + source.getName()
             + " to "
             + destination.getName()
             + " failed.",
         ex);
   } finally {
     if (sourceOpened) closeFolder(source, false);
     if (destinationOpened) closeFolder(destination, false);
   }
 }
  @Override
  protected void doDispose() {
    if (null != folder && folder.isOpen()) {
      try {

        folder.close(true);
      } catch (Exception e) {
        logger.debug("ignoring exception: " + e.getMessage(), e);
      }
    }
  }
Exemplo n.º 30
-1
  public static void main(String[] args) throws Exception {
    String pop3Server = "pop.163.com";
    String protocol = "pop3";
    String user = "******";
    String pwd = "kissyou770";

    Properties properties = new Properties();
    properties.setProperty("mail.store.protocol", protocol);
    properties.setProperty("mail.pop3.host", pop3Server);

    Session session = Session.getInstance(properties);
    session.setDebug(true);

    Store store = session.getStore();
    store.connect(pop3Server, user, pwd);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);

    Message[] messages = folder.getMessages();

    int mailCounts = messages.length;

    // for (Message message : messages) {
    Message message = messages[mailCounts - 1];
    new MyMail().mailReceiver(message);
    folder.close(false);
    store.close();
  }