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();
    }
  }
  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();
  }
  public boolean connectToMailBox() {
    try {
      Properties props = new Properties();
      props.setProperty("mail.imap.ssl.enable", "true"); // required for Gmail
      props.setProperty("mail.imap.auth.mechanisms", "XOAUTH2");
      props.setProperty("mail.store.protocol", config.getString("imap.protocol"));
      props.setProperty("mail.imaps.fetchsize", "" + fetchSize);
      props.setProperty("mail.imaps.timeout", "" + rTimeout);
      props.setProperty("mail.imaps.writetimeout", "" + rTimeout);
      props.setProperty("mail.imaps.connectiontimeout", "" + cTimeout);
      props.setProperty("mail.imaps.connectionpooltimeout", "" + cTimeout);

      Session session = Session.getInstance(props);
      mailbox = session.getStore(config.getString("imap.protocol"));
      mailbox.connect(
          config.getString("imap.host"),
          config.getString("imap.user"),
          config.getString("imap.access_token"));
      LOG.info("Connected to mailbox");
      return true;
    } catch (MessagingException e) {
      LOG.error("Connection failed", e);
      return false;
    }
  }
Exemple #4
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("не удалось поместить письмо в папку отправленные");
    }
  }
Exemple #5
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;
  }
Exemple #6
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();
  }
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
  @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;
  }
  @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);
  }
Exemple #10
0
 public void testConnect() {
   try {
     store.addConnectionListener(this);
     store.connect();
     assertNotNull(event);
     assertEquals(event.getType(), ConnectionEvent.OPENED);
   } catch (MessagingException e) {
     fail(e.getMessage());
   }
 }
 /**
  * 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;
 }
  /**
   * Connects to the message store (mail server).
   *
   * @return Message store.
   * @throws MessagingException On connection failure.
   */
  public Store getStore() throws MessagingException {
    // build the URL
    URLName url =
        new URLName("imap", mailServerName, mailServerPort, "", mailUsername, mailPassword);

    Session session = Session.getInstance(sessionProperties, null);

    Store store = new IMAPSSLStore(session, url);
    store.connect();

    return store;
  }
 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);
 }
 public void connect() throws IOException, ConfigurationException {
   if (!credentialsLoaded) {
     this.loadCredentials();
   }
   Properties props = new Properties();
   props.setProperty("mail.store.protocol", "imaps");
   Session session = Session.getInstance(props, null);
   try {
     store = session.getStore();
     store.connect(server, port, username, password);
   } catch (MessagingException e) {
     throw new IOException(e.getMessage());
   }
 }
  protected void renameMailbox(
      final Properties props, final String folderName, 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.renameTo(store.getFolder("renamed_from_" + folderName));

    logger.info("Renamed " + f.getFullName());
    store.close();
  }
Exemple #16
0
  // 连接邮件服务器
  public void connect() throws Exception {
    // 创建一个授权验证对象
    SmtpPop3Auth auth = new SmtpPop3Auth();
    auth.setAccount(user, password);

    // 取得一个Session对象
    Properties prop = new Properties();
    prop.put("mail.pop3.host", POP3Host);
    session = Session.getDefaultInstance(prop, auth);

    // 取得一个Store对象
    store = session.getStore("pop3");
    store.connect(POP3Host, user, password);
  }
  /**
   * <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 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);
    }
  }
 public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
   // Test connection to mail server
   if (evt.getNewValue() == CircuitBreaker.Status.on) {
     Session session = javax.mail.Session.getInstance(props, authenticator);
     session.setDebug(config.configuration().debug().get());
     try {
       Store store = session.getStore(url);
       store.connect();
       store.close();
     } catch (MessagingException e) {
       // Failed - don't allow to turn on circuit breaker
       throw new PropertyVetoException(e.getMessage(), evt);
     }
   }
 }
Exemple #20
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;
  }
  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();
    }
  }
Exemple #22
0
 public static Store getStore(String protocol, String host, String user, String password) {
   Properties properties = new Properties();
   properties.setProperty("mail.user", user);
   properties.setProperty("mail.host", host);
   Session session = Session.getInstance(properties);
   Store store;
   try {
     store = session.getStore(protocol);
     store.connect(host, user, password);
   } catch (NoSuchProviderException ex) {
     throw new RuntimeException(ex);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   return store;
 }
  /**
   * 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();
      }
    }
  }
  /**
   * 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());
    }
  }
  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;
  }
 public void ensureConnected() throws Exception {
   if (session == null) {
     Properties props = System.getProperties();
     props.setProperty("mail.store.protocol", "imaps");
     props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
     props.setProperty("mail.imap.socketFactory.fallback", "false");
     props.put("mail.smtp.host", getSmtpServer());
     session = Session.getDefaultInstance(props, null);
     store = session.getStore("imaps");
     try {
       store.connect(getServer(), getUsername(), getPassword());
     } catch (MessagingException e) {
       e.printStackTrace();
       System.exit(2);
     }
   }
 }
  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;
  }
Exemple #28
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;
 }
  /**
   * Funkcija koja se poziva pritiskom na određeni gumb i preusmjerava na temelju povratne
   * vrijednosti na željenu stranicu. Provjerava da li su uneseni podaci u log in-u ispravni.
   *
   * @return
   */
  public Boolean citajPoruke() {
    Session session = null;
    Store store = null;
    Folder folder = null;

    session = Session.getDefaultInstance(System.getProperties(), null);
    try {

      store = session.getStore("imap");
      store.connect(this.getEmailPosluzitelj(), this.getEmailKorisnik(), this.getEmailLozinka());
      uspjesnostAutentifikacije = true;
      return uspjesnostAutentifikacije;

    } catch (AuthenticationFailedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (FolderClosedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (FolderNotFoundException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (NoSuchProviderException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (ReadOnlyFolderException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (StoreClosedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (Exception e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    }
  }
Exemple #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();
  }