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:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*from   ww  w.ja  v a  2s  . c o m*/
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // 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++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            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();
                }
            }

            // 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 Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from w w w. ja  v a  2  s . c o  m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:org.apache.hupa.server.handler.ReplyMessageHandler.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected List getAttachments(ReplyMessage action) throws MessagingException, ActionException {
    List<?> items = new ArrayList();
    IMAPStore store = cache.get(getUser());

    IMAPFolder folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName());
    if (folder.isOpen() == false) {
        folder.open(Folder.READ_ONLY);
    }/*  www  .j  a  v a2s.  c  om*/

    // Only original inline images have to be added to the list 
    Message msg = folder.getMessageByUID(action.getReplyMessageUid());
    try {
        items = MessageUtils.extractInlineImages(logger, msg.getContent());
        if (items.size() > 0)
            logger.debug("Replying a message, extracted: " + items.size() + " inline image from");
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Put into the list the attachments uploaded by the user
    items.addAll(super.getAttachments(action));

    return items;
}

From source file:org.apache.hupa.server.handler.ForwardMessageHandler.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected List getAttachments(ForwardMessage action) throws MessagingException, ActionException {
    List<?> items = new ArrayList();
    IMAPStore store = cache.get(getUser());

    IMAPFolder folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName());
    if (folder.isOpen() == false) {
        folder.open(Folder.READ_ONLY);
    }//ww  w . ja va2  s . co m
    // Put the original attachments in the list 
    Message msg = folder.getMessageByUID(action.getReplyMessageUid());
    try {
        items = MessageUtils.extractMessageAttachments(logger, msg.getContent());
        logger.debug("Forwarding a message, extracted: " + items.size() + " from original.");
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Put in the list the attachments uploaded by the user
    items.addAll(super.getAttachments(action));
    return items;
}

From source file:org.jevis.emaildatasource.EmailForTest.java

public void testMail() throws MessagingException {
    List<InputStream> answerList = new ArrayList<InputStream>();

    _userName = "artur.iablokov@envidatec.com";
    _password = "na733aya";
    _host = "imap.1und1.de";

    Properties props = new Properties();
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "imaps");
    _session = Session.getInstance(props);
    _store = _session.getStore();/*from  w ww. j  a  v a  2 s .  c o m*/
    _store.connect(_host, _userName, _password);
    if (!_store.isConnected()) {
        System.out.println("Connected not possible");
    }
    _folderName = "INBOX"; // TODO
    _folder = _store.getFolder(_folderName);
    _folder.open(Folder.READ_ONLY);

    System.out.println("//////////Folder open!/////");

    InputStream answer = null;

    //channel parameter bekommen
    String sender = "support@jevis.de";
    String subject = "testinfo";
    Date lastReadout = new Date(1459658993827L);
    System.out.println("channel parameters: " + sender + " " + subject + " " + lastReadout);
    //richtige E-Mail(-s) finden
    SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, lastReadout);
    SearchTerm senderTerm = null;
    try {
        senderTerm = new FromTerm(new InternetAddress(sender));
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    SearchTerm subjectTerm = new SubjectTerm(subject);
    SearchTerm andTerm = new AndTerm(newerThan, new AndTerm(senderTerm, subjectTerm));
    System.out.println(andTerm.toString());
    List<Message> messageList = null;
    try {
        messageList = Arrays.asList(_folder.search(andTerm));
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //
    _folder.close(false);
    System.out.println("Folder closed");
    _store.close();
    System.out.println("Store closed");

    /**
     * List<File> attachments = new ArrayList<File>(); for (Message message
     * : messageList) { try { Multipart multipart = (Multipart)
     * message.getContent(); for (int i = 0; i < multipart.getCount(); i++)
     * { BodyPart bodyPart = multipart.getBodyPart(i); if
     * (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
     * !StringUtils.isNotBlank(bodyPart.getFileName())) { // !Checks if a
     * String is not empty (""), not null and not whitespace only. continue;
     * // dealing with attachments only } InputStream is =
     * bodyPart.getInputStream(); File file = new File("/tmp/" +
     * bodyPart.getFileName()); FileOutputStream fos = new
     * FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead;
     * while ((bytesRead = is.read(buf)) != -1) { fos.write(buf, 0,
     * bytesRead); } fos.close(); attachments.add(file);
        }*
     */

    /*for (int i = 0; i < answerList.size(); i++) {
        System.out.print(answerList.get(i).toString());
        }*/
}

From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java

/**
 * Loads the messages/*from  w  ww . j  a v a 2s. com*/
 * @throws MessagingException if unable to open the folder
 */
private void loadMessages() throws MessagingException {
    logger.debug("Loading message and folder information");
    inbox = store.getDefaultFolder();

    logger.debug("Opened folder");
    inbox.open(Folder.READ_ONLY);

    messageCount = inbox.getMessageCount();
    logger.info("MBox file is loaded and contains " + messageCount + " to be processed");
}

From source file:org.apache.hupa.server.servlet.MessageSourceServlet.java

/**
 * Handle to write back the requested attachment
 *//*from w w w. j a va 2  s. c o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    OutputStream outs = null;
    try {
        long uid = Long.parseLong(message_uuid);

        IMAPStore store = cache.get(user);
        IMAPFolder f = (IMAPFolder) store.getFolder(folderName);
        if (f.isOpen() == false) {
            f.open(Folder.READ_ONLY);
        }

        Message m = f.getMessageByUID(uid);

        response.setContentType("text/plain");
        outs = response.getOutputStream();
        m.writeTo(outs);
        outs.flush();

        if (f.isOpen()) {
            f.close(false);
        }
    } catch (Exception e) {
        String msg = "Unable to get raw content of msg for user " + user + " in folder " + folderName
                + " with uid " + message_uuid;
        logger.error(msg, e);
        throw new ServletException(msg, e);
    } finally {
        IOUtils.closeQuietly(outs);
    }
}

From source file:com.treesbearfruit.icloudnotes.NotesSaver.java

private void save(Store store, String wheretobackup, String f) throws MessagingException, IOException {

    System.out.println("opening folder " + f);
    Folder folder = store.getFolder(f);/*from  w  w w .java  2s.c om*/
    folder.open(Folder.READ_ONLY);

    FileUtils.forceMkdir(new File(wheretobackup));

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++) {
        // String from = (message[i].getFrom()[0]).toString();
        String subj = (message[i].getSubject()).toString();
        String nota = (message[i].getContent()).toString();

        // System.out.println("from: " + from);
        System.out.println("saving: " + subj);

        // BACKUP NOTE
        generals.writeFile(wheretobackup + "/" + generals.makeFilename(subj).trim() + ".html", nota,
                message[i].getSentDate());

    }
    folder.close(false);
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public void getMessage(cfImapConnection imapConnection, String rootFolder, long messageID, String _attachURI,
        String _attachDIR) throws cfmRunTimeException {
    try {//from w  ww .j a  v  a 2  s.c  o  m
        Folder folderToList;

        if (rootFolder == null || rootFolder.length() == 0)
            folderToList = imapConnection.mailStore.getDefaultFolder();
        else
            folderToList = imapConnection.mailStore.getFolder(rootFolder);

        if ((folderToList.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (!folderToList.isOpen())
                folderToList.open(Folder.READ_ONLY);

            boolean bResult = false;
            if (folderToList instanceof UIDFolder)
                bResult = extractMessage(((UIDFolder) folderToList).getMessageByUID(messageID), messageID,
                        _attachURI, _attachDIR);
            else
                bResult = extractMessage(folderToList.getMessage((int) messageID), messageID, _attachURI,
                        _attachDIR);

            if (!bResult)
                imapConnection.setStatus(false, "Message does not exist");
            else
                imapConnection.setStatus(true, "");

            folderToList.close(false);
        }

    } catch (Exception E) {
        imapConnection.setStatus(false, E.getMessage());
    }
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void readBounceAccount() throws MessagingException {
    Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*"));
    Store store = session.getStore("pop3");

    store.connect();//from  ww w .j av  a2  s  . c o  m

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

    if (folder.hasNewMessages()) {
        // Get directory
        Message message[] = folder.getMessages();
        BounceFacade bounceFacade = new BounceFacade();

        for (Message msg : message) {
            boolean isBounce = bounceFacade.processBounce(msg);
            if (isBounce) {
                msg.setFlag(Flags.Flag.SEEN, true);
                msg.saveChanges();
            }
        }
    }

}