Exemplo n.º 1
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;
  }
  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();
  }
  /**
   * 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);
    }
  }
  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();
  }
Exemplo n.º 5
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.º 6
0
  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();
      }
    }
  }
Exemplo n.º 7
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("не удалось поместить письмо в папку отправленные");
    }
  }
Exemplo n.º 8
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.º 9
0
  public static Folder getFolder(Store 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.º 10
0
 public void testGetFolder() {
   try {
     Folder f = store.getFolder(url.getFile());
     assertNotNull(f);
   } catch (MessagingException e) {
     fail(e.getMessage());
   }
 }
Exemplo n.º 11
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.º 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());
   }
 }
  @Override
  protected void doConnect() throws Exception {
    if (folder == null || !folder.isOpen()) {
      Store store = castConnector().getSessionDetails(endpoint).newStore();

      EndpointURI uri = endpoint.getEndpointURI();
      String encoding = endpoint.getEncoding();
      String user = (uri.getUser() != null ? URLDecoder.decode(uri.getUser(), encoding) : null);
      String pass =
          (uri.getPassword() != null ? URLDecoder.decode(uri.getPassword(), encoding) : null);
      store.connect(uri.getHost(), uri.getPort(), user, pass);

      folder = store.getFolder(castConnector().getMailboxFolder());
      ensureFolderIsOpen(folder);

      if (castConnector().getMoveToFolder() != null) {
        moveToFolder = store.getFolder(castConnector().getMoveToFolder());
        ensureFolderIsOpen(moveToFolder);
      }
    }
  }
 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);
 }
Exemplo n.º 15
0
  /**
   * <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();
  }
Exemplo n.º 16
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);
    }
  }
  @Override
  protected void doConnect() throws Exception {
    SessionDetails session = castConnector().getSessionDetails(endpoint);

    Store store = session.newStore();
    store.connect();
    folder = store.getFolder(castConnector().getMailboxFolder());
    if (castConnector().getMoveToFolder() != null) {
      moveToFolder = store.getFolder(castConnector().getMoveToFolder());
      moveToFolder.open(Folder.READ_WRITE);
    }

    // set default value if empty/null
    if (StringUtils.isEmpty(backupFolder)) {
      this.backupFolder =
          connector.getMuleContext().getConfiguration().getWorkingDirectory()
              + "/mail/"
              + folder.getName();
    }

    if (backupFolder != null && !this.backupFolder.endsWith(File.separator)) {
      this.backupFolder += File.separator;
    }
  }
Exemplo n.º 18
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();
    }
  }
  /**
   * 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();
      }
    }
  }
  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;
  }
  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;
  }
Exemplo n.º 22
0
  @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);
  }
Exemplo n.º 23
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;
 }
  private Object receiveMail() throws Exception {
    Folder folder = null;
    Store store = null;
    ConfigurationPropertyManager configManager =
        ConfigurationPropertyManager.getConfigurationPropertyManager();
    final String email_address = configManager.getPropValues("gmail_address");
    final String password = configManager.getPropValues("gmail_pw");

    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");

      // Session session = Session.getDefaultInstance(props, null);
      Session session = Session.getInstance(props, new GMailAuthenticator(email_address, password));
      store = session.getStore("imaps");
      store.connect("imap.gmail.com", email_address, password);
      folder = store.getFolder("Inbox");
      folder.open(Folder.READ_WRITE);
      // Message messages[] = folder.getMessages();
      // search for all "unseen" messages
      Flags seen = new Flags(Flags.Flag.SEEN);
      FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
      Message messages[] = folder.search(unseenFlagTerm);

      for (int i = 0; i < messages.length; i++) {
        folder.getMessage(
            messages[i].getMessageNumber()); // this will mark the retrieved messages as READ	    	
      }
      String s = updateEmailrepository(messages);
      // System.out.println(s);
      StringTerm st = new StringTermImpl(s);
      return st;

    } catch (Exception e) {
      System.out.println(e.toString());
    } finally {
      if (folder != null) {
        folder.close(true);
      }
    }
    return null;
  }
  public static void main(String[] args) throws Throwable {
    String mailbox = null;
    boolean DEBUG = false;

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-debug")) {
        DEBUG = true;

      } else if (mailbox == null) {
        mailbox = args[i];

      } else {
        usage("Spurious command line: " + args);
      }
    }

    if (mailbox == null) {
      usage("Missing mailbox");
    }

    // Get a connection to the mail server
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(DEBUG);

    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
      Provider provider = providers[i];
      out.println(provider);
    }

    Store store = session.getStore("imap");
    Folder folder = store.getFolder(mailbox);
    Message[] messages = folder.getMessages();
    out.println("Folder " + folder.getName() + " with " + messages.length + " messages");
    for (int i = 0; i < messages.length; i++) {
      Message message = messages[i];
      out.println("  " + i + ": " + message.getSubject());
    }

    out.println("");
  }
  public Message[] getMessages(
      String imapHost,
      String imapPort,
      String timeout,
      String username,
      String password,
      String folderName)
      throws MessagingException {
    store = getStore(imapHost, imapPort, timeout, username, password);

    // open the inbox folder

    folder = store.getFolder(folderName);
    folder.open(Folder.READ_WRITE);

    // get a list of java mail messages as an array of messages
    Message[] messages = folder.getMessages();

    return messages;
  }
Exemplo n.º 27
0
  public static void main(String args[]) throws Exception {
    // String host = args[0];
    // String username = args[1];
    // String password = args[2];

    String host = "triggeremails.com";
    String username = "******";
    String password = "******";

    // Get session
    Session session = Session.getInstance(System.getProperties(), null);

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

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++) {
      System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());

      System.out.println("Do you want to delete message? [YES to delete]");
      String line = reader.readLine();
      // Mark as deleted if appropriate
      if ("YES".equals(line)) {
        message[i].setFlag(Flags.Flag.DELETED, true);
      }
    }

    // Close connection
    folder.close(true);
    store.close();
  }
 public MimeMessage getMessage(String emailSetId, String mailId) {
   String hql =
       "from EmailUserSetting emailset where emailset.id = '" + Integer.valueOf(emailSetId) + "'";
   EmailUserSetting emailUserSetting = emailUserSettingDao.findEmailUserSetting(hql);
   Properties props = new Properties();
   Session session = Session.getDefaultInstance(props, null);
   Store store = null;
   Message message[] = null;
   try {
     store = session.getStore("pop3");
     store.connect(
         emailUserSetting.getPopService(),
         emailUserSetting.getEmailAddress(),
         emailUserSetting.getPassword());
     Folder folder = store.getFolder("INBOX");
     folder.open(Folder.READ_ONLY);
     message = folder.getMessages();
   } catch (NoSuchProviderException e) {
     e.printStackTrace();
   } catch (MessagingException e) {
     e.printStackTrace();
   }
   // System.out.println("Messages's length: "+message.length);
   MimeMessage pmm = null;
   for (int i = 0; i < message.length; i++) {
     pmm = (MimeMessage) message[i];
     String eId = null;
     try {
       eId = pmm.getMessageID();
     } catch (MessagingException e) {
       e.printStackTrace();
     }
     if (eId != null && eId.equals(mailId)) {
       return pmm;
     }
   }
   return null;
 }
Exemplo n.º 29
0
  protected void initialise(UMOEndpointURI endpoint) throws MessagingException {
    if (!initialised.get()) {
      String inbox = null;
      if (connector.getProtocol().equals("imap") && endpoint.getParams().get("folder") != null) {
        inbox = (String) endpoint.getParams().get("folder");
      } else {
        inbox = Pop3Connector.MAILBOX;
      }

      URLName url =
          new URLName(
              endpoint.getScheme(),
              endpoint.getHost(),
              endpoint.getPort(),
              inbox,
              endpoint.getUsername(),
              endpoint.getPassword());

      session = MailUtils.createMailSession(url);
      session.setDebug(logger.isDebugEnabled());

      Store store = session.getStore(url);
      store.connect();
      folder = store.getFolder(inbox);
      if (!folder.isOpen()) {
        try {
          // Depending on Server implementation it's not always
          // necessary
          // to open the folder to check it
          // Opening folders can be exprensive!
          // folder.open(Folder.READ_ONLY);
          folder.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
          logger.warn("Failed to open folder: " + folder.getFullName(), 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();
  }