Example usage for javax.mail Folder open

List of usage examples for javax.mail Folder open

Introduction

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

Prototype

public abstract void open(int mode) throws MessagingException;

Source Link

Document

Open this Folder.

Usage

From source file:com.ieprofile.helper.gmail.OAuth2Authenticator.java

/**
 * Connects and authenticates to an IMAP server with OAuth2. You must have
 * called {@code initialize}./*from  ww w.  j  a va 2s .  c o m*/
 *
 * @param host Hostname of the imap server, for example {@code
 *     imap.googlemail.com}.
 * @param port Port of the imap server, for example 993.
 * @param userEmail Email address of the user to authenticate, for example
 *     {@code oauth@gmail.com}.
 * @param oauthToken The user's OAuth token.
 * @param debug Whether to enable debug logging on the IMAP connection.
 *
 * @return An authenticated IMAPStore that can be used for IMAP operations.
 */
public List<MessageBean> connectToImap(String host, int port, String userEmail, String oauthToken,
        boolean debug) throws Exception {
    Properties props = new Properties();
    props.put("mail.imaps.sasl.enable", "true");
    props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
    props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
    Session session = Session.getInstance(props);
    session.setDebug(debug);

    final URLName unusedUrlName = null;
    IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
    final String emptyPassword = "";
    store.connect(host, port, userEmail, emptyPassword);
    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_WRITE);
    Message messages[] = inbox.getMessages();
    int messageCount = inbox.getMessageCount();
    List<String> attachments = new ArrayList<String>();
    LinkedList<MessageBean> listMessages = emailListener.sendMessage(messages, attachments);
    emailRepo.addAllMessages(listMessages);

    emailListener.folder = inbox;
    emailListener.started = false;
    emailListener.start();

    //ArrayList<String> attachments = new ArrayList<String>();
    //LinkedList<MessageBean> listMessages = getPart(messages, attachments);

    //store.close();
    return emailRepo.getMessages();
}

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: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;/*from ww  w .  j  av a  2  s.  c  om*/

    try {
        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:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }//from www . ja va  2s.  c  o m

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java

private Message getMessage(String requestMsgId) throws Exception {
    MimeMessage response = null;// w  ww.j a v  a2 s  .  c  o  m
    Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
    folder.open(Folder.READ_WRITE);
    Message[] msgs = folder.getMessages();
    log.debug(msgs.length + " messages in mailbox");
    loop: for (Message m : msgs) {
        MimeMessage mimeMessage = (MimeMessage) m;
        String[] inReplyTo = mimeMessage.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
        log.debug("Found message " + mimeMessage.getMessageID() + " in reply to " + Arrays.toString(inReplyTo));
        if (inReplyTo != null && inReplyTo.length > 0) {
            for (int j = 0; j < inReplyTo.length; j++) {
                if (requestMsgId.equals(inReplyTo[j])) {
                    log.debug("Identified message " + mimeMessage.getMessageID() + " as the response to "
                            + requestMsgId + "; retrieving it from the store");
                    // We need to create a copy so that we can delete the original and close the folder
                    response = new MimeMessage(mimeMessage);
                    log.debug("Flagging message " + mimeMessage.getMessageID() + " for deletion");
                    mimeMessage.setFlag(Flags.Flag.DELETED, true);
                    break loop;
                }
            }
        }
        log.warn("Don't know what to do with message " + mimeMessage.getMessageID() + "; skipping");
    }
    folder.close(true);
    return response;
}

From source file:com.agiletec.plugins.jpwebmail.apsadmin.webmail.folder.WebmailAction.java

public List<Message> getMessages() throws Throwable {
    List<Message> messageList = null;
    try {/*from w ww .j  av a  2 s  .c  om*/
        Folder folder = this.getCurrentFolder();
        folder.open(Folder.READ_ONLY);
        CurrentFolderMessagesInfo folderInfos = (CurrentFolderMessagesInfo) this.getRequest().getSession()
                .getAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES);
        //if (this.hasToReloadMessages(folder, folderInfos)) {
        Message messages[] = folder.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);
        this.setOpenedFolder(folder);
        messageList = Arrays.asList(messages);
        this.orderMessages(messageList);
        folderInfos = new CurrentFolderMessagesInfo(this.getCurrentFolderName(), messageList);
        this.getRequest().getSession().setAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES,
                folderInfos);
        //} else {
        //   messageList = folderInfos.getMessages();
        //}
    } catch (Throwable t) {
        _logger.error("Error extracting messages", t);
        throw t;
    }
    return messageList;
}

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

@Override
public void processMessages() {
    try {//from  ww  w  .j  av a2s.c o  m
        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:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java

@Override
public void processMessages() {
    try {//  w w  w  .j  a  va2  s.  c  o  m
        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.ikon.util.MailUtils.java

/**
 * Import messages/*from   w  w w  .  j a v a2s  .  c  om*/
 * 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;
}