Пример #1
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);
   }
 }
Пример #2
0
  /** {@inheritDoc} */
  @Override
  public String runImport(
      final GnucashWritableFile aWritableModel, final GnucashWritableAccount aCurrentAccount)
      throws Exception {
    try {
      Properties props = System.getProperties();
      Session session = Session.getDefaultInstance(props, null);
      Store store = session.getStore("imap");
      String server = aWritableModel.getUserDefinedAttribute("imap.server");
      if (server == null) {
        server =
            JOptionPane.showInputDialog(
                "imap-server: (can be changed later in the root-account properties.)");
        aWritableModel.setUserDefinedAttribute("imap.server", server);
      }
      String user = aWritableModel.getUserDefinedAttribute("imap.user");
      if (user == null) {
        user =
            JOptionPane.showInputDialog(
                "imap-user: (can be changed later in the root-account´s properties.)");
        aWritableModel.setUserDefinedAttribute("imap.user", user);
      }
      String passwd = JOptionPane.showInputDialog("imap-password:"******"mail folder opened");

      Message[] messages = folder.getMessages();
      for (Message message : messages) {
        try {
          if (importMessage(message, aCurrentAccount, aWritableModel)) {
            message.setFlag(Flag.SEEN, true);
            folder.copyMessages(new Message[] {message}, doneFolder);
            message.setFlag(Flags.Flag.DELETED, true);
          }
        } catch (Exception e) {
          LOG.log(Level.SEVERE, "Cannot import email" + message.getSubject(), e);
        }
      }
    } catch (Exception e) {
      LOG.log(Level.SEVERE, "Cannot scan mail-folder", e);
    }
    return null;
  }
  protected void deleteMailsFromUserMailbox(
      final Properties props,
      final String folderName,
      final int start,
      final int deleteCount,
      final String user,
      final String password)
      throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m =
        deleteCount == -1
            ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
      message.setFlag(Flag.DELETED, true);
      logger.info(
          "Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
      d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();
  }
  /**
   * @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;
  }
Пример #5
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);
  }
 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);
 }
  /**
   * 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);
    }
  }
Пример #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("не удалось поместить письмо в папку отправленные");
    }
  }
Пример #9
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;
  }
Пример #10
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();
  }
  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;
  }
Пример #12
0
 private void selectInbox() throws IOException {
   try {
     inbox = store.getFolder("INBOX");
     inbox.open(Folder.READ_ONLY);
     inboxSelected = true;
   } catch (MessagingException e) {
     throw new IOException(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);
  }
Пример #14
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;
  }
 private Message retrieveViaImap(String host, int port, String user, String password)
     throws MessagingException {
   Properties props = new Properties();
   props.setProperty("mail.store.protocol", "imap");
   props.setProperty("mail.imap.port", String.valueOf(port));
   Session session = Session.getInstance(props, null);
   Store store = session.getStore();
   store.connect(host, user, password);
   Folder inbox = store.getFolder("INBOX");
   inbox.open(Folder.READ_ONLY);
   int messageCount = inbox.getMessageCount();
   return messageCount == 0 ? null : inbox.getMessage(1);
 }
  /**
   * <b>使用IMAP协议接收邮件</b><br>
   *
   * <p>POP3和IMAP协议的区别: <b>POP3</b>协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上,<br>
   * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。<br>
   *
   * <p><b>IMAP</b>协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务
   * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会 即时反馈到服务器上。
   *
   * <p>两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端
   * 与webmail之间的双向同步功能很好地避免了这些问题。
   */
  public static void main(String[] args) throws Exception {
    // 准备连接服务器的会话信息
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imap");
    props.setProperty("mail.imap.host", "imap.qq.com");
    props.setProperty("mail.imap.port", "143");

    // 创建Session实例对象
    Session session = Session.getInstance(props);

    // 创建IMAP协议的Store对象
    Store store = session.getStore("imap");

    // 连接邮件服务器
    store.connect("*****@*****.**", "asdasd");

    // 获得收件箱
    Folder folder = store.getFolder("INBOX");
    // 以读写模式打开收件箱
    folder.open(Folder.READ_WRITE);

    // 获得收件箱的邮件列表
    Message[] messages = folder.getMessages();

    // 打印不同状态的邮件数量
    System.out.println("收件箱中共" + messages.length + "封邮件!");
    System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
    System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
    System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");

    System.out.println("------------------------开始解析邮件----------------------------------");

    // 解析邮件
    for (Message message : messages) {
      IMAPMessage msg = (IMAPMessage) message;
      String subject = MimeUtility.decodeText(msg.getSubject());
      System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String answer = reader.readLine();
      if ("yes".equalsIgnoreCase(answer)) {
        Pop3ReceiveMailUtil.parseMessage(msg); // 解析邮件
        // 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
        msg.setFlag(Flags.Flag.SEEN, true); // 设置已读标志
      }
    }

    // 关闭资源
    folder.close(false);
    store.close();
  }
 public MessagesWrapper markAsRead(List<Message> messagez)
     throws IOException, MessagingException {
   if (folder.isOpen() && folder.getMode() != Folder.READ_WRITE) {
     folder.close(true);
   }
   if (!folder.isOpen()) {
     folder.open(Folder.READ_WRITE);
   }
   for (Message message : messagez) {
     message.setFlag(Flags.Flag.SEEN, true);
   }
   logger.info("Marked email(s) as read : " + messagez.size());
   return this;
 }
Пример #18
0
  public static List<MailMessage> receiveMessages(
      String protocol,
      String host,
      String username,
      String password,
      boolean deleteReadMessages,
      boolean debug) {

    try {
      // Create empty properties
      Properties props = new Properties();
      props.put("mail.debug", (debug) ? "true" : "false");

      // Get session
      Session session =
          Session.getDefaultInstance(props, new UsrPwdAuthenticator(username, password));
      session.setDebug(debug);

      // Get the store
      Store store = session.getStore(protocol);
      store.connect(host, username, password);

      // Get folder
      Folder folder = store.getFolder("INBOX");
      folder.open(deleteReadMessages ? Folder.READ_WRITE : Folder.READ_ONLY);

      // Get messages
      Message[] messages = folder.getMessages();

      // Extract message info and mark messages for delete if requested
      List<MailMessage> msgs = new ArrayList<MailMessage>();
      for (int i = 0, n = messages.length; i < n; i++) {
        msgs.add(new MailMessage(messages[i]));
        if (deleteReadMessages) {
          messages[i].setFlag(Flags.Flag.DELETED, true);
        }
      }

      // Close connection
      folder.close(deleteReadMessages);
      store.close();

      return msgs;
    } catch (NoSuchProviderException e) {
      throw new RuntimeException(e);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Пример #19
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;
  }
 protected void ensureFolderIsOpen(Folder fldr) {
   if (!fldr.isOpen()) {
     try {
       // Depending on Server implementation it's not always
       // necessary to open the folder to check it
       // Opening folders can be exprensive!
       fldr.open(Folder.READ_WRITE);
     } catch (MessagingException e) {
       logger.warn(
           "Failed to open folder: "
               + fldr.getFullName()
               + " This is not an exception since some server implementations do not require the folder to be open",
           e);
     }
   }
 }
Пример #21
0
  public List<MyMessage> listAll() throws Exception {
    Store store = this.session.getStore();
    store.connect();
    try {

      Folder folder = store.getFolder(folderName);
      folder.open(Folder.READ_ONLY);
      List<MyMessage> msgs = map(folder.getMessages());
      folder.close(false);

      return msgs;

    } finally {
      store.close();
    }
  }
Пример #22
0
  public Message[] getLatestMessages(String theFolder, int num) throws MessagingException {
    // Open main "INBOX" folder.
    Folder folder = getFolder(theFolder);
    folder.open(Folder.READ_WRITE);

    int totalMessages = folder.getMessageCount();

    // Get folder's list of messages.
    Message[] messages = folder.getMessages(totalMessages - num, totalMessages);

    // Retrieve message headers for each message in folder.
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    profile.add(FetchProfile.Item.CONTENT_INFO);
    folder.fetch(messages, profile);
    return messages;
  }
  public List<MailInfo> receive() throws Exception {

    // TODO: externalize ....
    // mail server connection parameters
    // String host = "SSL0.OVH.NET";
    // String user = "******";
    // String password = "******";

    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties pop3Props = new Properties();
    pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
    pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
    pop3Props.setProperty("mail.pop3.port", port);
    pop3Props.setProperty("mail.pop3.socketFactory.port", port);

    URLName url = new URLName("pop3", host, Integer.parseInt(port), "", user, password);

    Session session = Session.getInstance(pop3Props, null);
    Store store = new POP3SSLStore(session, url);
    store.connect();

    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_WRITE);

    // get the list of inbox messages
    Message[] messages = inbox.getMessages();

    if (messages.length == 0) log.info("No messages found.");

    List<MailInfo> mails = new ArrayList<>();

    for (int i = 0; i < messages.length; i++) {
      MailInfo mail = new MailInfo();
      writePart(messages[i], mail);

      mails.add(mail);

      // TO REACTIVATE ...
      messages[i].setFlag(Flags.Flag.DELETED, true);
    }

    inbox.close(true);
    store.close();

    return mails;
  }
  /**
   * Test that FolderClosedException is thrown when the timeout occurs when reading the message
   * body.
   */
  @Test
  public void testFolderClosedExceptionBody() {
    TestServer server = null;
    try {
      final POP3Handler handler = new POP3HandlerTimeoutBody();
      server = new TestServer(handler);
      server.start();
      Thread.sleep(1000);

      final Properties properties = new Properties();
      properties.setProperty("mail.pop3.host", "localhost");
      properties.setProperty("mail.pop3.port", "" + server.getPort());
      final Session session = Session.getInstance(properties);
      // session.setDebug(true);

      final Store store = session.getStore("pop3");
      try {
        store.connect("test", "test");
        final Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message msg = folder.getMessage(1);
        try {
          msg.getContent();
        } catch (IOException ioex) {
          // expected
          // first attempt detects error return from server
        }
        // second attempt detects closed connection from server
        msg.getContent();

        // Check
        assertFalse(folder.isOpen());
      } catch (FolderClosedException ex) {
        // success!
      } finally {
        store.close();
      }
    } catch (final Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    } finally {
      if (server != null) {
        server.quit();
      }
    }
  }
  private Message[] getMessages(String host, String user, String password)
      throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
      logger.info("Subject: " + m.getSubject());
      logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
      logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }
    return msgs;
  }
Пример #26
0
 // 分页邮件列表
 public Message[] receive(
     String smtpHost, String user, String password, Integer pageNum, Integer range)
     throws MessagingException {
   // Create empty properties
   Properties props = new Properties();
   // Get session
   Session session = Session.getDefaultInstance(props, null);
   // Get the store
   Store store = session.getStore("pop3");
   store.connect(smtpHost, user, password);
   // Get folder
   Folder folder = store.getFolder("INBOX");
   folder.open(Folder.READ_ONLY);
   // Get directory
   Message[] message = null;
   if ((null != pageNum && pageNum != 0) && (null != range && range != 0)) {
     Integer count = folder.getMessageCount();
     Integer start = count - (pageNum * range) + 1;
     if (start < 0) {
       start = 1;
     }
     Integer end = count - ((pageNum - 1) * range);
     if (end < 0) {
       end = 10;
     }
     message = folder.getMessages(start, end);
   } else {
     message = folder.getMessages();
   }
   for (int i = message.length - 1; i >= 0; i--) {
     System.out.println(
         i
             + ": "
             + message[i].getFrom()[0]
             + "\t"
             + message[i].getSubject()
             + "\t"
             + DateUtils.DateToString(message[i].getSentDate()));
   }
   // Close connection
   folder.close(false);
   store.close();
   return message;
 }
  @Override
  public void poll() {
    boolean done = false;
    while (!done) {
      synchronized (folderLock) {
        if (getLifecycleState().isStopping() || getLifecycleState().isStopped()) {
          break;
        }
        try {
          try {
            if (!folder.isOpen()) {
              folder.open(Folder.READ_WRITE);
            }
          } catch (Exception e) {
            if (logger.isDebugEnabled()) {
              logger.debug("ignoring exception: " + e.getMessage());
            }
          }

          int count = folder.getMessageCount();
          int batchSize = getBatchSize(count);
          if (count > 0) {
            Message[] messages = folder.getMessages(1, batchSize);
            MessageCountEvent event =
                new MessageCountEvent(folder, MessageCountEvent.ADDED, true, messages);
            messagesAdded(event);
          } else if (count == -1) {
            throw new MessagingException(
                "Cannot monitor folder: " + folder.getFullName() + " as folder is closed");
          }
          done = batchSize >= count;
        } catch (MessagingException e) {
          done = true;
          getConnector().getMuleContext().getExceptionListener().handleException(e);
        } finally {
          try {
            folder.close(true); // close and expunge deleted messages
          } catch (Exception e) {
            logger.error("Failed to close pop3  inbox: " + e.getMessage());
          }
        }
      }
    }
  }
Пример #28
0
  public void scanWholeFolder() throws MessagingException {
    if (folder.isOpen() == false) {
      folder.open(Folder.READ_WRITE);
    }

    // Bulk-fetch the message envelopes.
    Message[] newMessages = folder.getMessages();
    FetchProfile fetchProfile = new FetchProfile();
    // FIXME: add CONTENT_INFO if we start to display the size
    // fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
    fetchProfile.add(FetchProfile.Item.ENVELOPE);
    fetchProfile.add(FetchProfile.Item.FLAGS);
    folder.fetch(newMessages, fetchProfile);

    this.messages = new ArrayList<Message>();
    messages.addAll(Arrays.asList(newMessages));

    fireTableDataChanged();
  }
Пример #29
0
  public IMAPConnection(URL url) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    //    session.setDebug(true);
    //    try {
    //      session.setDebugOut(new PrintStream(new FileOutputStream("foobar.txt")));
    //    } catch (FileNotFoundException e) {
    //      e.printStackTrace();  //To change body of catch statement use File | Settings | File
    // Templates.
    //    }

    store = (IMAPStore) session.getStore(url.getProtocol());

    String username = null;
    String password = null;

    String userinfo = url.getUserInfo();
    if (userinfo != null) {
      String[] parts = userinfo.split(":");

      username = parts[0].replace('=', '@');

      if (parts.length > 1) password = parts[1];
    }

    if (username == null) username = System.getProperty("imapfs.username");

    if (password == null) password = System.getProperty("imapfs.password");

    store.connect(url.getHost(), username, password);

    String path = url.getPath();
    if (path.startsWith("/")) path = path.substring(1);
    String[] parts = path.split(";");

    if (parts != null && parts.length > 0) this.folder = store.getFolder(parts[0]);
    else this.folder = store.getDefaultFolder();

    if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES);

    folder.open(Folder.READ_WRITE);
  }
Пример #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();
  }