List of usage examples for javax.mail Folder getMessages
public synchronized Message[] getMessages() throws MessagingException
From source file:MainClass.java
public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1);//from w w w . ja va 2s . c om } folder.open(Folder.READ_ONLY); // Get the messages from the server Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { // Get the headers System.out.println("From: " + InternetAddress.toString(messages[i].getFrom())); System.out.println("Reply-to: " + InternetAddress.toString(messages[i].getReplyTo())); System.out.println( "To: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.TO))); System.out.println( "Cc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.CC))); System.out.println( "Bcc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.BCC))); System.out.println("Subject: " + messages[i].getSubject()); System.out.println("Sent: " + messages[i].getSentDate()); System.out.println("Received: " + messages[i].getReceivedDate()); if (messages[i].isSet(Flags.Flag.DELETED)) { System.out.println("Deleted"); } if (messages[i].isSet(Flags.Flag.ANSWERED)) { System.out.println("Answered"); } if (messages[i].isSet(Flags.Flag.DRAFT)) { System.out.println("Draft"); } if (messages[i].isSet(Flags.Flag.FLAGGED)) { System.out.println("Marked"); } if (messages[i].isSet(Flags.Flag.RECENT)) { System.out.println("Recent"); } if (messages[i].isSet(Flags.Flag.SEEN)) { System.out.println("Read"); } if (messages[i].isSet(Flags.Flag.USER)) { // We don't know what the user flags might be in advance // so they're returned as an array of strings String[] userFlags = messages[i].getFlags().getUserFlags(); for (int j = 0; j < userFlags.length; j++) { System.out.println("User flag: " + userFlags[j]); } } } folder.close(false); }
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void main(String[] args) throws NoSuchProviderException, MessagingException { System.out.println("Salut"); // trustSSL(); /* final Properties props = new Properties(); props.put("mail.smtp.host", "my-mail-server"); props.put("mail.from", "me@example.com"); javax.mail.Session session = javax.mail.Session.getInstance(props, null); try {// w ww. jav a2s .c o m MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, "you@example.com"); msg.setSubject("JavaMail hello world example"); msg.setSentDate(new Date()); msg.setText("Hello, world!\n"); Transport.send(msg); } catch (MessagingException mex) { System.out.println("send failed, exception: " + mex); }*/ final Properties props = new Properties(); //props.put("mail.host", "10.69.60.6"); //props.put("mail.user", "fenyo"); //props.put("mail.from", "fenyo@fenyo.net"); //props.put("mail.transport.protocol", "smtps"); //props.put("mail.store.protocol", "pop3s"); // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]] // final Provider[] providers = session.getProviders(); javax.mail.Session session = javax.mail.Session.getInstance(props, null); session.setDebug(true); //session.setDebug(false); // final Store store = session.getStore("pop3s"); // store.connect("10.69.60.6", 995, "fenyo", "PASSWORD"); // final Store store = session.getStore("imaps"); // store.connect("10.69.60.6", 993, "fenyo", "PASSWORD"); // System.out.println(store.getDefaultFolder().getMessageCount()); //final Store store = session.getStore("pop3"); final Store store = session.getStore("pop3s"); //final Store store = session.getStore("imaps"); // store.addStoreListener(new StoreListener() { // public void notification(StoreEvent e) { // String s; // if (e.getMessageType() == StoreEvent.ALERT) // s = "ALERT: "; // else // s = "NOTICE: "; // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage()); // } // }); //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD"); store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD"); //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD"); //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD"); //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD"); // final Folder[] folders = store.getPersonalNamespaces(); // for (Folder f : folders) { // System.out.println("Folder: " + f.getMessageCount()); // final Folder g = f.getFolder("INBOX"); // g.open(Folder.READ_ONLY); // System.out.println(" g:" + g.getMessageCount()); // } final Folder inbox = store.getDefaultFolder().getFolder("INBOX"); inbox.open(Folder.READ_ONLY); System.out.println("nmessages: " + inbox.getMessageCount()); final Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("message:"); System.out.println(" size: " + message.getSize()); try { if (message.getFrom() != null) System.out.println(" From: " + message.getFrom()[0]); } catch (final Exception ex) { System.out.println(ex.toString()); } System.out.println(" content-type: " + message.getContentType()); System.out.println(" disposition: " + message.getDisposition()); System.out.println(" description: " + message.getDescription()); System.out.println(" filename: " + message.getFileName()); System.out.println(" line count: " + message.getLineCount()); System.out.println(" message number: " + message.getMessageNumber()); System.out.println(" subject: " + message.getSubject()); try { if (message.getAllRecipients() != null) for (Address address : message.getAllRecipients()) System.out.println(" address: " + address); } catch (final Exception ex) { System.out.println(ex.toString()); } } for (Message message : messages) { System.out.println("-----------------------------------------------------"); Object content; try { content = message.getContent(); if (javax.mail.Multipart.class.isInstance(content)) { System.out.println("CONTENT OBJECT CLASS: MULTIPART"); final javax.mail.Multipart multipart = (javax.mail.Multipart) content; System.out.println("multipart content type: " + multipart.getContentType()); System.out.println("multipart count: " + multipart.getCount()); for (int i = 0; i < multipart.getCount(); i++) { System.out.println(" multipart body[" + i + "]: " + multipart.getBodyPart(i)); BodyPart part = multipart.getBodyPart(i); System.out.println(" content-type: " + part.getContentType()); } } else if (String.class.isInstance(content)) { System.out.println("CONTENT IS A STRING: {" + content + "}"); } else { System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString()); } } catch (IOException e) { e.printStackTrace(); } } store.close(); }
From source file:msgshow.java
public static void main(String argv[]) { int optind;/*from www.j ava 2s . co m*/ InputStream msgStream = System.in; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-D")) { debug = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-p")) { port = Integer.parseInt(argv[++optind]); } else if (argv[optind].equals("-s")) { showStructure = true; } else if (argv[optind].equals("-S")) { saveAttachments = true; } else if (argv[optind].equals("-m")) { showMessage = true; } else if (argv[optind].equals("-a")) { showAlert = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[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] [-f msg-file]"); System.exit(1); } else { break; } } try { // 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; if (mbox != null) msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox))); else msg = new MimeMessage(session, msgStream); dumpPart(msg); 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); } if (mbox == null) mbox = "INBOX"; 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 (optind >= argv.length) { // 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 { while (optind < argv.length) { int msgnum = Integer.parseInt(argv[optind++]); System.out.println("Getting message number: " + msgnum); Message m = null; try { m = folder.getMessage(msgnum); dumpPart(m); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:MainClass.java
public static void main(String argv[]) { int msgnum = -1; int optind;//from w w w. j a va 2s . c o m InputStream msgStream = System.in; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-D")) { debug = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-p")) { port = Integer.parseInt(argv[++optind]); } else if (argv[optind].equals("-s")) { showStructure = true; } else if (argv[optind].equals("-S")) { saveAttachments = true; } else if (argv[optind].equals("-m")) { showMessage = true; } else if (argv[optind].equals("-a")) { showAlert = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[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] [-f msg-file]"); System.exit(1); } else { break; } } try { if (optind < argv.length) msgnum = Integer.parseInt(argv[optind]); // 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; if (mbox != null) msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox))); else msg = new MimeMessage(session, msgStream); dumpPart(msg); 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); } if (mbox == null) mbox = "INBOX"; 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 { System.out.println("Getting message number: " + msgnum); Message m = null; try { m = folder.getMessage(msgnum); dumpPart(m); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:Main.java
public static List<Message> getMessagesWithPage(Folder folder, int pageNum, int pageSize) throws MessagingException { Message[] messages = folder.getMessages(); Arrays.sort(messages, new Comparator<Message>() { public int compare(Message o1, Message o2) { Message m1 = (Message) o1;/* www .ja va2 s . c o m*/ Message m2 = (Message) o2; if (m1.getMessageNumber() > m2.getMessageNumber()) { return -1; } return 1; } }); List<Message> list = Arrays.asList(messages); int start = (pageNum - 1) * pageSize; int end = pageNum * pageSize; return list.subList(start, end); }
From source file:populate.java
/** * Copy message from src to dst. If dontPreserveFlags is set we first copy the * messages to memory, clear all the flags, and then copy to the destination. *///from w ww . j av a2 s.c om private static void copyMessages(Folder src, Folder dst) throws MessagingException { Message[] msgs = src.getMessages(); if (dontPreserveFlags) { for (int i = 0; i < msgs.length; i++) { MimeMessage m = new MimeMessage((MimeMessage) msgs[i]); m.setFlags(m.getFlags(), false); msgs[i] = m; } } src.copyMessages(msgs, dst); }
From source file:populate.java
/** * Copy message from src to dst. If dontPreserveFlags is set * we first copy the messages to memory, clear all the flags, * and then copy to the destination.//from ww w. ja v a 2s. c om */ private static void copyMessages(Folder src, Folder dst) throws MessagingException { Message[] msgs = src.getMessages(); if (dontPreserveFlags) { for (int i = 0; i < msgs.length; i++) { MimeMessage m = new MimeMessage((MimeMessage) msgs[i]); m.setFlags(m.getFlags(), false); msgs[i] = m; } } if (warn) { // have to copy messages one at a time for (int i = 0; i < msgs.length; i++) { try { src.copyMessages(new Message[] { msgs[i] }, dst); } catch (MessagingException mex) { System.out.println("WARNING: Copy of message " + (i + 1) + " from " + src.getFullName() + " to " + dst.getFullName() + " failed: " + mex.toString()); } } } else src.copyMessages(msgs, dst); }
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Check whether email received by reading the emails. * * @param protocol to connect to the store * @param user whose mail store should be connected * @param subject the subject of the mail to search * @return//from w ww . java2 s. c om * @throws MessagingException when unable to connect to the store */ public static boolean isMailReceived(String protocol, GreenMailUser user, String subject) throws MessagingException { Store store = getConnection(user, protocol); Folder folder = store.getFolder(EMAIL_INBOX); folder.open(Folder.READ_ONLY); boolean isReceived = false; Message[] messages = folder.getMessages(); for (Message message : messages) { if (message.getSubject().contains(subject)) { log.info("Found the Email with Subject : " + subject); isReceived = true; break; } } return isReceived; }
From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java
/** * gets all current messages from the mail server and returns the number * of messages containing the string, messages containing the string are * deleted from the mail server String is the body of each message * * @return number of matching and deleted messages * @param contains a string to search for *///from ww w. j a v a 2s .co m private static int fetchMail(String contains) { //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; /* Set the mail properties */ Properties properties = TckPublisher.getProperties(); // Set manual Properties int found = 0; Session session = Session.getDefaultInstance(properties, null); Store store = null; try { store = session.getStore("pop3"); store.connect(properties.getProperty("mail.pop3.host"), Integer.parseInt(properties.getProperty("mail.pop3.port", "110")), properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password")); /* Mention the folder name which you want to read. */ // inbox = store.getDefaultFolder(); // inbox = inbox.getFolder("INBOX"); Folder inbox = store.getFolder("INBOX"); /* Open the inbox using store. */ inbox.open(Folder.READ_WRITE); Message messages[] = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream())); Enumeration allHeaders = p.getMimeMessage().getAllHeaders(); while (allHeaders.hasMoreElements()) { Object j = allHeaders.nextElement(); if (j instanceof javax.mail.Header) { javax.mail.Header msg = (javax.mail.Header) j; logger.info("XML as message header is " + msg.getValue()); if (msg.getValue().contains(contains)) { //found it messages[i].setFlag(Flags.Flag.DELETED, true); found++; } } } for (int k = 0; k < p.getAttachmentList().size(); k++) { InputStream is = p.getAttachmentList().get((k)).getInputStream(); QuotedPrintableCodec qp = new QuotedPrintableCodec(); // If "is" is not already buffered, wrap a BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) { is = new BufferedInputStream(is); } int c; StringBuilder sb = new StringBuilder(); System.out.println("Message : "); while ((c = is.read()) != -1) { sb.append(c); System.out.write(c); } is.close(); String decoded = qp.decode(sb.toString()); logger.info("decode message is " + decoded); if (decoded.contains(contains)) { //found it messages[i].setFlag(Flags.Flag.DELETED, true); found++; } } } inbox.close(true); } catch (Exception ex) { ex.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (Exception ex) { } } } return found; }
From source file:org.wso2.es.ui.integration.util.ESUtil.java
private static String getMailWithSubject(Folder inbox, String subject) throws MessagingException, InterruptedException, IOException { int pollCount = 0; while ((pollCount <= MAX_MAIL_POLL)) { Message[] messages = inbox.getMessages(); for (int i = messages.length - 1; i >= 0; i--) { Message message = messages[i]; if (subject.equals(message.getSubject())) { Object content = message.getContent(); if (content instanceof String) { return (String) content; } else { throw new AssertionError("non text email content in email titled " + subject); }/*from www. ja v a 2 s . c om*/ } } Thread.sleep(MAIL_WAIT_TIME); } return null; }