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; }
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(); }
/** * Endpoint can be in the form of pop3://username:[email protected] * * @param endpointUri * @param timeout * @return * @throws Exception */ public UMOMessage receive(UMOEndpointURI endpointUri, long timeout) throws Exception { initialise(endpointUri); long t0 = System.currentTimeMillis(); if (timeout < 0) { timeout = Long.MAX_VALUE; } do { int count = folder.getMessageCount(); if (count > 0) { Message message = folder.getMessage(1); // so we don't get the same message again message.setFlag(Flags.Flag.DELETED, true); return new MuleMessage(connector.getMessageAdapter(message)); } else if (count == -1) { throw new MessagingException( "Cannot monitor folder: " + folder.getFullName() + " as folder is closed"); } long sleep = Math.min(this.connector.getCheckFrequency(), timeout - (System.currentTimeMillis() - t0)); if (sleep > 0) { if (logger.isDebugEnabled()) { logger.debug("No results, sleeping for " + sleep); } Thread.sleep(sleep); } else { logger.debug("Timeout"); return null; } } while (true); }
/** @return */ public int getTotalMessageCount() throws Exception { Folder f = getFolder(); if (f.exists()) { return f.getMessageCount(); } return 0; }
/** * Retrieves headers of new messages. * * @return a string array containing the message headers */ public String[] getNewMessageHeaders() throws Exception { logger.info("[Inbound:MailServerFolder] Calling getNewMessageHeaders"); reopen(); // Make sure the folder is open // // Deliver only new messages to the MDB // try { if (folder.hasNewMessages()) { int newMsgs = folder.getNewMessageCount(); int msgCount = folder.getMessageCount(); Message[] msgs = folder.getMessages(msgCount - newMsgs + 1, msgCount); String[] headers = new String[msgs.length]; logger.log(Level.INFO, "messages length: {0}", msgs.length); logger.log(Level.INFO, "headers length: {0}", headers.length); for (int i = 0; i < headers.length; i++) { logger.log( Level.INFO, "[Inbound:MailServerFolder] Packing message with SUBJECT: {0}", msgs[i].getSubject()); headers[i] = msgs[i].getSubject(); } return headers; } } catch (Exception e) { logger.severe("[Inbound:MailServerFolder] Exception obtaining messages from mail server:"); } return null; }
@Override 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; }
public int getNumberOfEmails() throws IOException { if (!inboxSelected) { this.selectInbox(); } try { return inbox.getMessageCount(); } catch (MessagingException e) { throw new IOException(e.getMessage()); } }
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); }
protected boolean areMessagesInReverseOrder(Folder inbox) throws MessagingException { try { Message msgFirst = inbox.getMessage(1); Message msgLast = inbox.getMessage(inbox.getMessageCount()); Date firstMessageDate = getDateToDetermineOrder(msgFirst); Date lastMessageDate = getDateToDetermineOrder(msgLast); return firstMessageDate != null && lastMessageDate != null && firstMessageDate.after(lastMessageDate); } catch (Exception e) { return false; } }
public Collection<Integer> getFirstTimeMessages(Folder inbox, String context) throws Exception { log.debug(String.format("handling first mailcheck for %s", context)); Collection<Integer> messages = new ArrayList<Integer>(); // we need to get 5 most recent messages in this case if (inbox.getMessageCount() > 0) { if (areMessagesInReverseOrder(inbox)) { log.debug(String.format("order is reverse chronological for %s", context)); for (int i = 0; i < 5; i++) { messages.add(i + 1); } } else { log.debug(String.format("order is chronological for %s", context)); for (int messageNumber = inbox.getMessageCount(); messageNumber > 0 && messageNumber > inbox.getMessageCount() - 5; messageNumber--) { messages.add(messageNumber); } } } return messages; }
public Message[] getLatestMessages(String theFolder, int num) throws MessagingException { // Open main "INBOX" folder. Folder folder = getFolder(theFolder); folder.open(Folder.READ_WRITE); int totalMessages = folder.getMessageCount(); // Get folder's list of messages. Message[] messages = folder.getMessages(totalMessages - num, totalMessages); // Retrieve message headers for each message in folder. FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); profile.add(FetchProfile.Item.CONTENT_INFO); folder.fetch(messages, profile); return messages; }
// 分页邮件列表 public Message[] receive( String smtpHost, String user, String password, Integer pageNum, Integer range) throws MessagingException { // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store Store store = session.getStore("pop3"); store.connect(smtpHost, user, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message[] message = null; if ((null != pageNum && pageNum != 0) && (null != range && range != 0)) { Integer count = folder.getMessageCount(); Integer start = count - (pageNum * range) + 1; if (start < 0) { start = 1; } Integer end = count - ((pageNum - 1) * range); if (end < 0) { end = 10; } message = folder.getMessages(start, end); } else { message = folder.getMessages(); } for (int i = message.length - 1; i >= 0; i--) { System.out.println( i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject() + "\t" + DateUtils.DateToString(message[i].getSentDate())); } // Close connection folder.close(false); store.close(); return message; }
@Override public void poll() { boolean done = false; while (!done) { synchronized (folderLock) { if (getLifecycleState().isStopping() || getLifecycleState().isStopped()) { break; } try { try { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("ignoring exception: " + e.getMessage()); } } int count = folder.getMessageCount(); int batchSize = getBatchSize(count); if (count > 0) { Message[] messages = folder.getMessages(1, batchSize); MessageCountEvent event = new MessageCountEvent(folder, MessageCountEvent.ADDED, true, messages); messagesAdded(event); } else if (count == -1) { throw new MessagingException( "Cannot monitor folder: " + folder.getFullName() + " as folder is closed"); } done = batchSize >= count; } catch (MessagingException e) { done = true; getConnector().getMuleContext().getExceptionListener().handleException(e); } finally { try { folder.close(true); // close and expunge deleted messages } catch (Exception e) { logger.error("Failed to close pop3 inbox: " + e.getMessage()); } } } } }
/** * Retrieves new messages. * * @return an array of messages */ public Message[] getNewMessages() throws Exception { logger.info("[Inbound:MailServerFolder] Calling getNewMessages"); reopen(); // Make sure the folder is open // // Deliver only new messages to the MDB // try { if (folder.hasNewMessages()) { int newMsgs = folder.getNewMessageCount(); int msgCount = folder.getMessageCount(); Message msgs[] = folder.getMessages(msgCount - newMsgs + 1, msgCount); return msgs; } } catch (Exception e) { logger.info("[Inbound:MailServerFolder] Exception obtaining messages from mail server"); } return null; }
private void receiveMail() { String username = USERNAME; String password = PASSWORD; try { ServerConfigProvider provider = ServerConfigFactory.fromEmailAdress(username); MailReceiver mailReceiver = new MailReceiver(provider, new User(username, password)); for (Folder folders : mailReceiver.getFolders()) { try { System.out.println(folders.getFullName() + " " + folders.getMessageCount()); } catch (Exception e) { System.err.println(e.getMessage()); } } Folder folder = mailReceiver.getFolderByName("Inbox"); folder.open(Folder.READ_ONLY); for (Message message : folder.getMessages()) { List<File> attachments = MessageHelper.getAttachments(Environment.getExternalStorageDirectory(), message); if (!attachments.isEmpty()) { for (File attachment : attachments) { System.out.println( String.format( "from %s subject %s attachmentname %s", message.getFrom()[0], message.getSubject(), attachment.getName())); } } else { System.out.println( String.format( "from %s subject %s no attachement", message.getFrom()[0], message.getSubject())); } } mailReceiver.close(); } catch (Exception e) { e.printStackTrace(); } }
public MessageIterator(Folder folder, int batchSize) throws EmailFetchException { try { this.folder = folder; this.batchSize = batchSize; SearchTerm st = getSearchTerm(); if (st != null) { doBatching = false; messagesInCurBatch = folder.search(st); totalInFolder = messagesInCurBatch.length; folder.fetch(messagesInCurBatch, fp); current = 0; LOG.info("Total messages: {}", totalInFolder); LOG.info("Search criteria applied. Batching disabled."); } else { totalInFolder = folder.getMessageCount(); LOG.info("Total messages: {}", totalInFolder); getNextBatch(batchSize, folder); } } catch (MessagingException e) { throw new EmailFetchException("Message retreival failed", e); } }
/** * Receive Email from POPServer. Use POP3 protocal by default. Thus, call this method, you need to * provide a pop3 mail server address. * * @param emailAddress The email account in the POPServer. * @param password The password of email address. */ public static void receiveEmail(String host, String username, String password) { // param check. If param is null, use the default configured value. if (host == null) { host = POP3Server; } if (username == null) { username = POP3Username; } if (password == null) { password = POP3Password; } Properties props = System.getProperties(); // MailAuthenticator authenticator = new MailAuthenticator(username, password); try { Session session = Session.getDefaultInstance(props, null); // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); // Connect POPServer store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); if (inbox == null) { throw new RuntimeException("No inbox existed."); } // Open the INBOX with READ_ONLY mode and start to read all emails. inbox.open(Folder.READ_ONLY); System.out.println("TOTAL EMAIL:" + inbox.getMessageCount()); Message[] messages = inbox.getMessages(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String from = InternetAddress.toString(msg.getFrom()); String replyTo = InternetAddress.toString(msg.getReplyTo()); String to = InternetAddress.toString(msg.getRecipients(Message.RecipientType.TO)); String subject = msg.getSubject(); Date sent = msg.getSentDate(); Date ress = msg.getReceivedDate(); String type = msg.getContentType(); System.out.println((i + 1) + ".---------------------------------------------"); System.out.println("From:" + mimeDecodeString(from)); System.out.println("Reply To:" + mimeDecodeString(replyTo)); System.out.println("To:" + mimeDecodeString(to)); System.out.println("Subject:" + mimeDecodeString(subject)); System.out.println("Content-type:" + type); if (sent != null) { System.out.println("Sent Date:" + sdf.format(sent)); } if (ress != null) { System.out.println("Receive Date:" + sdf.format(ress)); } // //Get message headers. // @SuppressWarnings("rawtypes") // Enumeration headers = msg.getAllHeaders(); // while (headers.hasMoreElements()) { // Header h = (Header) headers.nextElement(); // String name = h.getName(); // String val = h.getValue(); // System.out.println(name + ": " + val); // } // //get the email content. // Object content = msg.getContent(); // System.out.println(content); // //print content // Reader reader = new InputStreamReader( // messages[i].getInputStream()); // int a = 0; // while ((a = reader.read()) != -1) { // System.out.print((char) a); // } } // close connection. param false represents do not delete messaegs on server. inbox.close(false); store.close(); // } catch(IOException e) { // LOGGER.error("IOException caught while printing the email content", e); } catch (MessagingException e) { LOGGER.error("MessagingException caught when use message object", e); } }
/* (non-Javadoc) * @see org.claros.commons.mail.protocols.Protocol#connect(int) */ public ConnectionMetaHandler connect(int connectType) throws SystemException, ConnectionException, ServerDownException { Folder fold = null; try { if (handler == null || handler.getStore() == null || !handler.getStore().isConnected()) { Properties props = new Properties(); // props.setProperty("mail.imap.separatestoreconnection", "true"); // props.setProperty("mail.imap.connectionpoolsize", "0"); // props.setProperty("mail.imap.connectionpooltimeout", "100"); // props.setProperty("mail.debug", "true"); Session session = Session.getDefaultInstance(props); log.debug("session instance initiated"); handler = new ConnectionMetaHandler(); handler.setStore(session.getStore(profile.getProtocol())); log.debug("session store set. protocol is: " + profile.getProtocol()); handler .getStore() .connect( profile.getFetchServer(), profile.getIFetchPort(), auth.getUsername(), auth.getPassword()); if (handler.getStore().isConnected()) { log.debug("Store has been connected... Successful"); } else { log.warn("Connection unsuccessfull...!!"); } } fold = handler.getStore().getFolder(Constants.FOLDER_INBOX(profile)); HashMap imapUserFolders = (HashMap) imapFolders.get(auth.getUsername()); imapUserFolders.put("INBOX", fold); imapFolders.put(auth.getUsername(), imapUserFolders); handler.setMbox(fold); log.debug("Got mailbox folder. Folder is: " + fold.getFullName()); handler.setTotalMessagesCount(fold.getMessageCount()); log.debug("Message Count:" + handler.getTotalMessagesCount()); } catch (FolderNotFoundException e) { log.fatal( profile.getProtocol() + " cannot identify the INBOX folder. Please check your folder-namespace variable at config.xml."); throw new SystemException(e); } catch (NoSuchProviderException e) { log.fatal(profile.getProtocol() + " provider could not be found."); throw new SystemException(e); } catch (MessagingException e) { Exception ne = e.getNextException(); if (ne != null) { if (ne instanceof ConnectException || ne instanceof IOException) { throw new ServerDownException("Server is unreachable."); } } log.error("Connection could not be established." + e.getMessage()); // throw new ConnectionException(e); } catch (Exception e) { log.error("An unknown exception while connect.", e); } return handler; }
protected int getMessageCount() throws MessagingException { return folder.getMessageCount(); }
public static void ClaimsMsgShow( java.lang.String argvs[], Folder folder, Store store, biz.systempartners.claims.ClaimsViewer claimsViewer) { if (claimsViewer == null) {} int msgnum = -1; int optind = 0; InputStream msgStream = System.in; if (argvs != null) { for (optind = 0; optind < argvs.length; optind++) { if (argvs[optind].equals("-T")) { protocol = argvs[++optind]; } else if (argvs[optind].equals("-H")) { host = argvs[++optind]; } else if (argvs[optind].equals("-U")) { user = argvs[++optind]; } else if (argvs[optind].equals("-P")) { password = argvs[++optind]; } else if (argvs[optind].equals("-v")) { verbose = true; } else if (argvs[optind].equals("-D")) { debug = true; } else if (argvs[optind].equals("-f")) { mbox = argvs[++optind]; } else if (argvs[optind].equals("-L")) { url = argvs[++optind]; } else if (argvs[optind].equals("-p")) { port = Integer.parseInt(argvs[++optind]); } else if (argvs[optind].equals("-s")) { showStructure = true; } else if (argvs[optind].equals("-S")) { saveAttachments = true; } else if (argvs[optind].equals("-m")) { showMessage = true; } else if (argvs[optind].equals("-a")) { showAlert = true; } else if (argvs[optind].equals("--")) { optind++; break; } else if (argvs[optind].startsWith("-")) { System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]"); System.out.println("or msgshow -m [-v] [-D] [-s] [-S] < msg"); System.exit(1); } else { break; } } } try { if (optind < argvs.length) msgnum = Integer.parseInt(argvs[optind]); // msgnum = 1; // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); if (showMessage) { MimeMessage msg = new MimeMessage(session, msgStream); dumpPart(msg, claimsViewer); // System.exit(0); } /* // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, port, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } */ // folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (msgnum == -1) { // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { Message[] msgs = folder.getMessages(); for (int n = 0; n < msgs.length; n++) { System.out.println("Getting message number: " + n + 1); Message m = null; try { m = folder.getMessage(msgnum + 1); // m.setDisposition( dumpPart(m, claimsViewer); // m.setExpunged(true); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); } // folder.expunge(); folder.close(true); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); // System.exit(1); } // System.exit(0); }