List of usage examples for javax.mail Folder open
public abstract void open(int mode) throws MessagingException;
From source file:msgshow.java
public static void main(String argv[]) { int optind;//from w w w . j av a 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 { // 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;/*w w w.jav a 2 s . c om*/ 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: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 www . j a v a 2 s.c o m*/ * @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 www . ja v a 2 s . com 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.apache.hupa.server.preferences.InImapUserPreferencesStorage.java
/** * Opens the IMAP folder and read messages until it founds the magic subject, * then gets the attachment which contains the data and return the serialized object stored. *///from www. ja v a2 s . co m protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName, String magicType) throws MessagingException, IOException, ClassNotFoundException { Folder folder = iStore.getFolder(folderName); if (folder.exists()) { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } Message message = null; Message[] msgs = folder.getMessages(); for (Message msg : msgs) { if (magicType.equals(msg.getSubject())) { message = msg; break; } } if (message != null) { Object con = message.getContent(); if (con instanceof Multipart) { Multipart mp = (Multipart) con; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) { ObjectInputStream ois = new ObjectInputStream(part.getInputStream()); Object o = ois.readObject(); ois.close(); logger.info("Returning user preferences of type " + magicType + " from imap folder + " + folderName + " for user " + user); return o; } } } } } return null; }
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Delete all emails in the inbox./*from ww w. j a v a 2s . c o m*/ * * @param protocol protocol used to connect to the server * @throws MessagingException if we're unable to connect to the store */ public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException { Folder inbox = null; Store store = getConnection(user, protocol); try { inbox = store.getFolder(EMAIL_INBOX); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (Message message : messages) { message.setFlag(Flags.Flag.DELETED, true); log.info("Deleted email Subject : " + message.getSubject()); } } finally { if (inbox != null) { inbox.close(true); } if (store != null) { store.close(); } } }
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Check mail folder for an email using subject. * * @param emailSubject Email subject//from www . jav a 2s. co m * @param folder mail folder to check for an email * @param protocol protocol used to connect to the server * @return whether mail received or not * @throws MessagingException if we're unable to connect to the store */ private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol, GreenMailUser user) throws MessagingException { boolean emailReceived = false; Folder mailFolder; Store store = getConnection(user, protocol); try { mailFolder = store.getFolder(folder); mailFolder.open(Folder.READ_WRITE); SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject)); Message[] messages = mailFolder.search(searchTerm); for (Message message : messages) { if (message.getSubject().contains(emailSubject)) { log.info("Found the Email with Subject : " + emailSubject); emailReceived = true; break; } } } finally { if (store != null) { store.close(); } } return emailReceived; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method delete all the sent mails. Can be used after a particular test class * * @throws MessagingException//from w ww . j ava 2s . c o m * @throws IOException */ public static void deleteSentMails() throws MessagingException, IOException { Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder sentMail = store.getFolder("[Gmail]/Sent Mail"); sentMail.open(Folder.READ_WRITE); Message[] messages = sentMail.getMessages(); Flags deleted = new Flags(Flags.Flag.DELETED); sentMail.setFlags(messages, deleted, true); sentMail.close(true); store.close(); }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read verification e-mail from Gmail inbox and returns the verification URL. * * @return verification redirection URL. * @throws Exception//from w w w .jav a2 s.c o m */ public static String readGmailInboxForVerification() throws Exception { boolean isEmailVerified = false; long waitTime = 10000; String pointBrowserURL = ""; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isEmailVerified) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains("EmailVerification")) { pointBrowserURL = getBodyFromMessage(message); isEmailVerified = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return pointBrowserURL; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read e-mails from Gmail inbox and find whether the notification of particular type is found. * * @param notificationType Notification types supported by publisher and store. * @return whether email is found for particular type. * @throws Exception/* ww w. j ava2 s. c o m*/ */ public static boolean readGmailInboxForNotification(String notificationType) throws Exception { boolean isNotificationMailAvailable = false; long waitTime = 10000; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isNotificationMailAvailable) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains(notificationType)) { isNotificationMailAvailable = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return isNotificationMailAvailable; }