Example usage for javax.mail Folder READ_ONLY

List of usage examples for javax.mail Folder READ_ONLY

Introduction

In this page you can find the example usage for javax.mail Folder READ_ONLY.

Prototype

int READ_ONLY

To view the source code for javax.mail Folder READ_ONLY.

Click Source Link

Document

The Folder is read only.

Usage

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

public Folder getFolder(String name) throws Exception {
    Store store = session.getStore("imaps");
    store.connect(IMAP_MAIL_SERVER, USER, password);
    Folder folder = store.getFolder(name);
    folder.open(Folder.READ_ONLY);
    return folder;
}

From source file:org.alfresco.repo.imap.RemoteLoadTester.java

public void testMailbox() {
    logger.info("Getting folder...");
    long t = System.currentTimeMillis();

    // Create empty properties
    Properties props = new Properties();
    props.setProperty("mail.imap.partialfetch", "false");

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    Store store = null;//from  w  ww .j  a v a2  s  . c o  m
    Folder folder = null;
    try {
        // Get the store
        store = session.getStore("imap");
        store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD);

        // Get folder
        folder = store.getFolder(TEST_FOLDER_NAME);
        folder.open(Folder.READ_ONLY);

        // Get directory
        Message message[] = folder.getMessages();

        for (int i = 0, n = message.length; i < n; i++) {
            message[i].getAllHeaders();

            Address[] from = message[i].getFrom();
            System.out.print(i + ": ");
            if (from != null) {
                System.out.print(message[i].getFrom()[0] + "\t");
            }
            System.out.println(message[i].getSubject());

            Object content = message[i].getContent();
            if (content instanceof MimeMultipart) {
                for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) {
                    BodyPart part = ((MimeMultipart) content).getBodyPart(j);
                    Object partContent = part.getContent();

                    if (partContent instanceof String) {
                        String body = (String) partContent;
                    } else if (partContent instanceof FilterInputStream) {
                        FilterInputStream fis = (FilterInputStream) partContent;
                        BufferedInputStream bis = new BufferedInputStream(fis);

                        /* while (bis.available() > 0) 
                         {
                            bis.read();
                         }*/
                        byte[] bytes = new byte[524288];
                        while (bis.read(bytes) != -1) {
                        }
                        bis.close();
                        fis.close();
                    }
                }
            }

            int nn = 0;

        }

        t = System.currentTimeMillis() - t;
        logger.info("Time: " + t + " ms (" + t / 1000 + " s)");
        logger.info("Length: " + message.length);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    } finally {
        // Close connection
        try {
            if (folder != null) {
                folder.close(false);
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            fail(e.getMessage());
        }
    }

}

From source file:it.unimi.di.big.mg4j.document.JavamailDocumentCollection.java

/** Builds a document collection corresponding to a given store URL and folder name.
 * /*www  .j  a  v  a2s .  c o  m*/
 *  <p><strong>Beware.</strong> This class is not suited for large mbox files!
 * 
 * @param storeUrl the javamail URL of the store.
 * @param folderName the folder name.
 * @param factory the factory that will be used to create documents.
 * @throws MessagingException 
 */
protected JavamailDocumentCollection(final String storeUrl, final String folderName,
        final JavamailDocumentFactory factory) throws MessagingException {
    this.storeUrl = storeUrl;
    this.folderName = folderName;
    this.factory = factory;

    this.store = SESSION.getStore(new URLName(storeUrl));
    store.connect();

    this.folder = store.getDefaultFolder().getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    this.numberOfMessages = folder.getMessageCount();
}

From source file:com.google.code.rptm.mailarchive.DefaultMailingListArchive.java

public void retrieveMessages(String mailingList, YearMonth month, MimeMessageProcessor processor,
        MailingListArchiveEventListener eventListener) throws MailingListArchiveException {
    Session session = Session.getDefaultInstance(new Properties());
    try {//from   w  w w .ja  va  2 s .  c o m
        Store store = session.getStore(new URLName("mstor:" + getMboxFile(mailingList, month, eventListener)));
        store.connect();
        try {
            Folder folder = store.getDefaultFolder();
            folder.open(Folder.READ_ONLY);
            for (Message msg : folder.getMessages()) {
                if (!processor.processMessage((MimeMessage) msg)) {
                    break;
                }
            }
        } finally {
            store.close();
        }
    } catch (MessagingException ex) {
        throw new MailingListArchiveException("JavaMail exception: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MailingListArchiveException("I/O exception: " + ex.getMessage(), ex);
    }
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from   ww w . j a  v a 2  s.co  m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.// w w  w  .  ja v a  2  s  .c o m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * Retrieve mail messages in a JSON representation
 * //from   ww w  .j  a va2 s.  c om
 * @return
 */
public JSONArray getJMessages() {

    JSONArray jMessages = new JSONArray();
    if (store == null)
        return jMessages;

    try {
        /*
         * Connect to IMAP store
         */
        store.connect();

        /*
         * Retrieve & open INBOX folder
         */
        Folder folder = store.getFolder(ImapConstants.INBOX);
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        for (int i = 0; i < messages.length; i++) {

            Message m = messages[i];

            JSONObject jMessage = new JSONObject();

            jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails             
            jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server

            jMessage.put(ImapConstants.J_SUBJECT, m.getSubject());
            jMessage.put(ImapConstants.J_DATE, m.getSentDate());

            String from = "";

            Address[] addresses = m.getFrom();
            for (Address address : addresses) {

                InternetAddress internetAddress = (InternetAddress) address;
                from = internetAddress.getPersonal();

            }

            jMessage.put(ImapConstants.J_FROM, from);

            FileUtil attachment = getAttachment(m);
            if (attachment == null) {
                jMessage.put(ImapConstants.J_ATTACHMENT, false);

            } else {
                jMessage.put(ImapConstants.J_ATTACHMENT, true);

            }

            jMessages.put(jMessages.length(), jMessage);

        }

        folder.close(false);
        store.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return jMessages;
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*  www .  j a  v a  2  s.  c  o m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

@Override
public AccountSummary fetchAccountSummaryFromStore(MailStoreConfiguration config, String username,
        String mailAccount, String folder, int start, int max) {

    Authenticator auth = credentialsProvider.getAuthenticator();

    AccountSummary summary;/*from   www . j  av  a 2s. c om*/
    Folder inbox = null;
    try {

        // Retrieve user's folder
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, folder);
        inbox.open(Folder.READ_ONLY);
        long startTime = System.currentTimeMillis();
        List<EmailMessage> messages = getEmailMessages(inbox, start, max, session);

        if (log.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            int messagesToDisplayCount = messages.size();
            log.debug("Finished looking up email messages. Inbox size: " + inbox.getMessageCount()
                    + " Unread message count: " + inbox.getUnreadMessageCount() + " Total elapsed time: "
                    + elapsedTime + "ms " + " Time per message in inbox: "
                    + (inbox.getMessageCount() == 0 ? 0 : (elapsedTime / inbox.getMessageCount())) + "ms"
                    + " Time per displayed message: "
                    + (messagesToDisplayCount == 0 ? 0 : (elapsedTime / messagesToDisplayCount)) + "ms");
        }

        IEmailLinkService linkService = linkServiceRegistry.getEmailLinkService(config.getLinkServiceKey());
        String inboxUrl = null;
        if (linkService != null) {
            inboxUrl = linkService.getInboxUrl(config);
        }

        // Initialize account information with information retrieved from inbox
        summary = new AccountSummary(inboxUrl, messages, inbox.getUnreadMessageCount(), inbox.getMessageCount(),
                start, max, isDeleteSupported(inbox), getQuota(inbox));

        if (log.isDebugEnabled()) {
            log.debug("Successfully retrieved email AccountSummary");
        }

        return summary;

    } catch (MailAuthenticationException mae) {
        // We used just to allow this exception to percolate up the chain,
        // but we learned that the entire stack trace gets written to
        // Catalina.out (by 3rd party code).  Since this is a common
        // occurrence, it causes space issues.
        return new AccountSummary(mae);
    } catch (MessagingException me) {
        log.error("Exception encountered while retrieving account info", me);
        throw new EmailPreviewException(me);
    } catch (IOException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } catch (ScanException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } catch (PolicyException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int todosCorreosNum(String name) {
    int num = 0;/*from  w  ww.j a  v  a 2 s.  co m*/
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());
        System.out.println("ola" + store);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        num = msg.length;
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
    return num;
}