Example usage for javax.mail Store getFolder

List of usage examples for javax.mail Store getFolder

Introduction

In this page you can find the example usage for javax.mail Store getFolder.

Prototype

public abstract Folder getFolder(URLName url) throws MessagingException;

Source Link

Document

Return a closed Folder object, corresponding to the given URLName.

Usage

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  a v a 2  s .c  om

    // 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();
            }
        }
    }

}

From source file:com.hs.mail.web.controller.FetchAccountFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    FetchAccount fetch = (FetchAccount) command;
    String userName = RequestUtils.getParameter(request, "destUserName");
    String password = RequestUtils.getParameter(request, "destPassword");
    Store store = null;
    try {/* w w w. jav a 2s .  co  m*/
        store = connect(userName, password);
        FetchMailer mailer = new FetchMailer(fetch, store.getFolder("INBOX"));
        mailer.fetch();
        return new ModelAndView(getSuccessView(), errors.getModel());
    } catch (Exception e) {
        return showForm(request, response, errors);
    } finally {
        if (store != null) {
            store.close();
        }
    }
}

From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java

public void saveAllAttachment() {
    String protocol = ssl ? "imaps" : "imap";

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

    try {//from   w ww .  ja  va  2s.  c om
        Session session = Session.getInstance(props);
        Store store = session.getStore();
        store.connect(host, port, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        for (Message msg : inbox.getMessages()) {
            if (!msg.isSet(Flags.Flag.SEEN)) {
                String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber();
                Multipart multipart = (Multipart) msg.getContent();
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart bodyPart = multipart.getBodyPart(i);
                    if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && StringUtils.isNotEmpty(bodyPart.getFileName())) {
                        MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= 
                        mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName()));
                        msg.setFlag(Flags.Flag.SEEN, true);
                    }
                }
            }
        }
    } catch (IOException | MessagingException e) {
        log.error("? ? ?,  : "
                + e.getMessage());
    }

}

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);//from  www.j a  v a2  s  .c  om
    return folder;
}

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);
    folder.open(Folder.READ_ONLY);/*from  w w  w  . j  a  v a  2  s.c om*/

    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:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java

@Override
public void processMessages() {
    try {/*from w ww. ja v  a  2  s .  c  om*/
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message messages[] = folder.search(ft);
            for (Message message : messages) {
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.SEEN), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}

From source file:com.yfiton.notifiers.email.EmailNotifierTest.java

private boolean checkEmailReception(String subject, String host, String username, String password)
        throws MessagingException {
    Properties properties = new Properties();
    properties.put("mail.store.protocol", "imaps");
    Session session = Session.getInstance(properties);

    Store store = null;

    try {//  w w  w.  ja v  a 2s.c o m
        store = session.getStore("imaps");
        store.connect(host, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                message.setFlag(Flags.Flag.DELETED, true);
                return true;
            }
        }

        inbox.close(true);
    } finally {
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    return false;
}

From source file:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java

@Override
public void processMessages() {
    try {// w  w w .  j a  v a2 s .  com
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            Message[] messages = folder.getMessages();
            for (Message message : messages) {
                backup(message);
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.DELETED), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}

From source file:com.szmslab.quickjavamail.receive.MailReceiver.java

/**
 * ????//  w  ww  .ja  v  a2s.c om
 *
 * @param callback
 *            ??1???
 * @throws Exception
 */
public void execute(ReceiveIterationCallback callback) throws Exception {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    Store store = null;
    Folder folder = null;
    try {
        store = session.getStore(properties.getProtocol());
        store.connect();

        folder = store.getFolder(folderName);
        folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE);

        final Message messages[] = folder.getMessages();
        for (Message message : messages) {
            MessageLoader loader = new MessageLoader(message, !readonly);
            boolean isContinued = callback.iterate(loader);
            if (!readonly && loader.isDeleted()) {
                message.setFlag(Flags.Flag.DELETED, loader.isDeleted());
            }
            if (!isContinued) {
                break;
            }
        }
    } finally {
        if (folder != null) {
            try {
                folder.close(!readonly);
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
    }
}

From source file:com.ikon.util.MailUtils.java

/**
 * Import messages/*from  ww  w  .  ja v  a 2s  .  co m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}