Example usage for javax.mail Store close

List of usage examples for javax.mail Store close

Introduction

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

Prototype

public synchronized void close() throws MessagingException 

Source Link

Document

Close this service and terminate its connection.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;
    Folder inbox = null;//www .  ja  v  a  2  s.  c  o m
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
   Disconnect from all Mailhosts//from www  . j  a  va  2s . c o  m
*/
public void disconnectAll() {
    Enumeration<String> e = user.mailHosts();
    while (e.hasMoreElements()) {
        String name = e.nextElement();
        disconnect(name);
    }
    Set<String> zapKeys = new HashSet<String>();
    for (Map.Entry<String, Store> storeEntry : stores.entrySet()) {
        Store st = storeEntry.getValue();
        try {
            st.close();
            log.info("Mail: Connection to " + st.toString() + " closed.");
        } catch (Exception ex) {
            log.warn("Mail: Failed to close connection to " + st.toString() + ". Reason: " + ex.getMessage());
        }
        zapKeys.add(storeEntry.getKey());
    }
    for (String key : zapKeys)
        stores.remove(key);
    folders = null;
}

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   w  w  w.j a  v a  2s  . c  om
    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:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

/**
 * Returns new messages and fetches details for each message.
 *///w  w w .j  a  va2s.  c  o m
@Transactional(readOnly = false)
public ResultClass<Boolean> downloadEmails() {

    ResultClass<Boolean> result = new ResultClass<>();
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    try {

        // connects to the message store
        Store store = session.getStore(protocol);

        store.connect(userName, password);
        // 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];

            String[] idHeaders = msg.getHeader("MESSAGE-ID");
            if (idHeaders != null && idHeaders.length > 0) {

                MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]);
                if (exists == null) {

                    MessageBox messageBox = new MessageBox();
                    messageBox.setSubject(msg.getSubject());
                    messageBox.setCode(idHeaders[0]);

                    Address[] fromAddresses = msg.getFrom();
                    String from = InternetAddress.toString(fromAddresses);

                    if (from.startsWith("=?")) {
                        from = MimeUtility.decodeWord(from);
                    }
                    messageBox.setFrom(from);
                    String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO));

                    if (to.startsWith("=?")) {
                        to = MimeUtility.decodeWord(to);
                    }
                    messageBox.setTo(to);

                    String[] replyHeaders = msg.getHeader("References");

                    if (replyHeaders != null && replyHeaders.length > 0) {
                        StringTokenizer tokens = new StringTokenizer(replyHeaders[0]);
                        MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken());
                        if (parent != null)
                            parent.addReply(messageBox);
                    }

                    result = parseSubjectAndCreate(messageBox, msg);
                }
            }
        }

        folderInbox.close(false);
        store.close();

        return result;

    } catch (NoSuchProviderException ex) {
        logger.error("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    result.setSingleElement(false);
    return result;
}

From source file:com.sonicle.webtop.core.app.WebTopManager.java

private void createCyrusUser(String login, String domainId) throws WTCyrusException {
    String host = wta.getSettingsManager().getServiceSetting(domainId, "com.sonicle.webtop.mail",
            BaseServiceSettings.DEFAULT_PREFIX + "host");
    int port = Integer.parseInt(wta.getSettingsManager().getServiceSetting(domainId, "com.sonicle.webtop.mail",
            BaseServiceSettings.DEFAULT_PREFIX + "port"));
    String protocol = wta.getSettingsManager().getServiceSetting(domainId, "com.sonicle.webtop.mail",
            BaseServiceSettings.DEFAULT_PREFIX + "protocol");
    String adminuser = wta.getSettingsManager().getServiceSetting(domainId, "com.sonicle.webtop.mail",
            "admin.user");
    String adminpass = wta.getSettingsManager().getServiceSetting(domainId, "com.sonicle.webtop.mail",
            "admin.password");
    Store s = getCyrusStore(host, port, protocol, adminuser, adminpass);
    createCyrusMailbox(login, s);// w w  w  .  ja  v a 2 s. com
    setCyrusAcl(login, login, s);
    setCyrusAcl(login, adminuser, s);
    try {
        s.close();
    } catch (Exception exc) {
    }
}

From source file:com.email.ReceiveEmail.java

/**
 * This account fetches emails from a specified account and marks the emails
 * as seen, only touches the email account does not delete or move any
 * information./*ww w .  jav a 2s.co  m*/
 *
 * @param account SystemEmailModel
 */
public static void fetchEmail(SystemEmailModel account) {
    Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
    Properties properties = EmailProperties.setEmailInProperties(account);

    try {
        Session session = Session.getInstance(properties, auth);
        Store store = session.getStore();
        store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(),
                account.getPassword());
        Folder fetchFolder = store.getFolder(account.getIncomingFolder());
        if (account.getIncomingFolder().trim().equals("")) {
            fetchFolder = store.getFolder("INBOX");
        }

        if (fetchFolder.exists()) {
            fetchFolder.open(Folder.READ_WRITE);
            Message[] msgs = fetchFolder.getMessages();

            // USE THIS FOR UNSEEN MAIL TO SEEN MAIL
            //Flags seen = new Flags(Flags.Flag.SEEN);
            //FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            //Message[] msgs = fetchFolder.search(unseenFlagTerm);
            //fetchFolder.setFlags(msgs, seen, true);
            if (msgs.length > 0) {
                List<String> messageList = new ArrayList<>();

                for (Message msg : msgs) {
                    boolean notDuplicate = true;
                    String headerText = Arrays.toString(msg.getHeader("Message-ID"));

                    for (String header : messageList) {
                        if (header.equals(headerText)) {
                            notDuplicate = false;
                            break;
                        }
                    }

                    if (notDuplicate) {
                        //Add to header to stop duplicates
                        messageList.add(headerText);
                        attachmentCount = 1;
                        attachmentList = new ArrayList<>();

                        //Setup Email For dbo.Email
                        EmailMessageModel eml = new EmailMessageModel();
                        String emailTime = String.valueOf(new Date().getTime());
                        eml.setSection(account.getSection());
                        eml = saveEnvelope(msg, msg, eml);
                        eml.setId(EMail.InsertEmail(eml));

                        //After Email has been inserted Gather Attachments
                        saveAttachments(msg, msg, eml);

                        //Create Email Body
                        eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList);

                        //Insert Email Body As Attachment (so it shows up in attachment table during Docketing)
                        EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName());

                        //Flag email As ready to file so it is available in the docket tab of SERB3.0
                        eml.setReadyToFile(1);
                        EMail.setEmailReadyToFile(eml);
                    }

                    if (deleteEmailEnabled) {
                        //  Will Delete message from server
                        //  Un Comment line below to run
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
            }
            fetchFolder.close(true);
            store.close();
        }
    } catch (MessagingException ex) {
        if (ex != null) {
            System.out.println("Unable to connect to email Server for: " + account.getEmailAddress()
                    + "\nPlease ensure you are connected to the network and" + " try again.");
        }
        ExceptionHandler.Handle(ex);
    }
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * {@inheritDoc}//from w  w  w. j  av  a  2s  . c o m
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
        return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
        if (StringUtils.isBlank(provider)) {
            provider = DEFAULT_PROVIDER;
        }
        account = new Account(ctx);
    } catch (IllegalArgumentException e) {
        throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

        // Connect to the server
        try {
            store = session.getStore(provider);
            store.connect(account.getHost(), account.getLogin(), account.getPassword());
        } catch (NoSuchProviderException e) {
            throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'",
                    e);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
        }

        // Open the account's inbox
        try {
            inbox = store.getFolder(INBOX);
            if (inbox == null)
                throw new JobException(this, "No inbox found at " + account);
            inbox.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to inbox at " + account, e);
        }

        // Get the messages from the server
        try {
            for (Message message : inbox.getMessages()) {
                if (!message.isSet(Flag.SEEN)) {
                    try {
                        Page page = aggregate(message, site);
                        message.setFlag(Flag.DELETED, true);
                        repository.put(page, true);
                        logger.info("E-Mail message published at {}", page.getURI());
                    } catch (Exception e) {
                        logger.info("E-Mail message discarded: {}", e.getMessage());
                        message.setFlag(Flag.SEEN, true);
                        // TODO: Reply to sender if the "from" field exists
                    }
                }
            }
        } catch (MessagingException e) {
            throw new JobException(this, "Error loading e-mail messages from inbox", e);
        }

        // Close the connection
        // but don't remove the messages from the server
    } finally {
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing inbox", e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing connection to e-mail server", e);
            }
        }
    }

}

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;
    Folder folder = null;//from  w w  w  .j  a v  a 2s  .  c  om
    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:com.ikon.util.MailUtils.java

/**
 * Import messages/*from   w w  w .  j av  a 2s.  c  o 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;
}

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

/**
 * Import messages/*from   w w  w . j a va  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);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.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;
}