Exemple #1
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 #2
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("не удалось поместить письмо в папку отправленные");
    }
  }
  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
  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();
      }
    }
  }
  @Test
  public void testGetFolder() throws MessagingException {
    Properties props;
    Session session;
    Folder folder;
    props = new Properties();

    props.put("mail.host", "pop.gmail.com");
    props.put("mail.store.protocol", "pop3s");
    props.put("mail.pop3s.auth", "true");
    props.put("mail.pop3s.port", 995);

    session = Session.getInstance(props, null);
    Store instance;

    // with wrong param
    instance = session.getStore();
    instance.connect("*****@*****.**", "spamreturn");
    try {
      folder = instance.getFolder("");
    } catch (MessagingException ex) {
      assertTrue(true);
    }

    // with valid param
    try {
      folder = instance.getFolder("INBOX");
      assertTrue(true);
    } catch (MessagingException ex) {
      fail("Should not throw MessagingException");
    }
  }
  @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);
  }
  @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;
  }
Exemple #9
0
 protected void setUp() {
   session = Session.getInstance(System.getProperties());
   // session.setDebug(true);
   try {
     store = session.getStore(url);
     assertNotNull(store);
   } catch (MessagingException e) {
     fail(e.getMessage());
   }
 }
 /**
  * 获取IMAP协议Store对象
  *
  * @param username
  * @param password
  * @return
  */
 @Override
 public IMAPStore connectImapService(String username, String password) throws MessagingException {
   // 创建Session实例对象
   Session session = Session.getInstance(props);
   // 创建IMAP协议的Store对象
   IMAPStore store = (IMAPStore) session.getStore("imap");
   // 连接邮件服务器
   store.connect(username, password);
   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 Store getStore(boolean useOldStores) throws MailException {
    Store store = null;

    try {
      String storeKey = _incomingHostName.concat(_outgoingHostName).concat(_login);

      if (useOldStores) {
        store = _allStores.get(storeKey);

        if ((store != null) && !store.isConnected()) {
          store.close();

          store = null;
        }
      }

      if (store == null) {
        Session session = getSession();

        if (_incomingSecure) {
          store = session.getStore("imaps");
        } else {
          store = session.getStore("imap");
        }

        store.addConnectionListener(new ConnectionListener(storeKey));
        store.connect(_incomingHostName, _incomingPort, _login, _password);

        if (useOldStores) {
          _allStores.put(storeKey, store);
        }
      }

      return store;
    } catch (MessagingException me) {
      throw new MailException(MailException.ACCOUNT_INCOMING_CONNECTION_FAILED, me);
    }
  }
 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());
   }
 }
Exemple #14
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);
     }
   }
 }
  public GoogleVoiceFolder connect(
      Account account, String context, StopWatch watch, GoogleVoiceProcess process)
      throws IOException, MessagingException {

    StopWatchUtils.newTask(watch, "Get session", context, log);
    Session session = Session.getInstance(getMailProperties(account));
    StopWatchUtils.newTask(watch, "Get store", context, log);
    Store store = session.getStore("pop3");
    GoogleVoiceFolder inbox = new GoogleVoiceFolder(session, process.getVoice());

    StopWatchUtils.newTask(watch, "Open folder", context, log);
    inbox.open(Folder.READ_ONLY);

    return inbox;
  }
Exemple #19
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;
  }
Exemple #20
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;
 }
  /**
   * 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 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);
     }
   }
 }
  /**
   * 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;
  }
Exemple #25
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 #27
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);
  }
  public synchronized void connect(Properties props) throws Exception {
    String username = getUsername();
    String password = getPassword();
    String server = getServer();

    props.put("mail.smtp.host", getSmtpServer());

    session = Session.getDefaultInstance(props, null);
    store = session.getStore("imaps");

    // smtps://username%[email protected]/

    try {
      store.connect(server, username, password);
    } catch (MessagingException e) {
      e.printStackTrace();
      System.exit(2);
    }
  }
  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("");
  }
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();
  }