List of usage examples for javax.mail Store connect
public void connect(String user, String password) throws MessagingException
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *//* w ww . jav a2s.c om*/ @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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void renameMailbox(final Properties props, final String folderName, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password); checkStoreForTestConnection(store);// w ww . j a v a 2s.co m final Folder f = store.getFolder(folderName); f.renameTo(store.getFolder("renamed_from_" + folderName)); logger.info("Renamed " + f.getFullName()); store.close(); }
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password); checkStoreForTestConnection(store);// w ww.j a v a 2 s.c o m final Folder f = store.getFolder(folderName); f.open(Folder.READ_WRITE); final int msgCount = f.getMessageCount(); final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1)); int d = 0; for (final Message message : m) { message.setFlag(Flag.DELETED, true); logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject()); d++; } f.close(true); logger.info("Deleted " + d + " messages"); store.close(); }
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void createInitialIMAPTestdata(final Properties props, final String user, final String password, final int count, final boolean deleteall) throws MessagingException { final Session session = Session.getInstance(props); final Store store = session.getStore(); store.connect(user, password); checkStoreForTestConnection(store);/* w w w . j a va2s . c o m*/ final Folder root = store.getDefaultFolder(); final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS"); final Folder testrootl2 = testroot.getFolder("Level(2!"); if (deleteall) { deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password); if (testroot.exists()) { testroot.delete(true); } final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS"); if (testrootenamed.exists()) { testrootenamed.delete(true); } } if (!testroot.exists()) { testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testroot.open(Folder.READ_WRITE); testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testrootl2.open(Folder.READ_WRITE); } final Folder inbox = root.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final Message[] msgs = new Message[count]; for (int i = 0; i < count; i++) { final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL_TO)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS)); message.setSubject(EMAIL_SUBJECT + "::" + i); message.setText(EMAIL_TEXT + "::" + SID++); message.setSentDate(new Date()); msgs[i] = message; } inbox.appendMessages(msgs); testroot.appendMessages(msgs); testrootl2.appendMessages(msgs); IMAPUtils.close(inbox); IMAPUtils.close(testrootl2); IMAPUtils.close(testroot); IMAPUtils.close(store); }
From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java
private Object getMessage(String requestMsgId) { Session session = Session.getInstance(props, null); session.setDebug(log.isTraceEnabled()); Store store = null; try {// w ww . ja v a 2s.c o m store = session.getStore("pop3"); store.connect(username, password); Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER); folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); log.debug(msgs.length + " replies in reply mailbox"); for (Message m : msgs) { String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO); log.debug("Got reply to : " + Arrays.toString(inReplyTo)); if (inReplyTo != null && inReplyTo.length > 0) { for (int j = 0; j < inReplyTo.length; j++) { if (requestMsgId.equals(inReplyTo[j])) { m.setFlag(Flags.Flag.DELETED, true); return m.getContent(); } } } m.setFlag(Flags.Flag.DELETED, true); } folder.close(true); } catch (Exception e) { e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException ignore) { } store = null; } } return null; }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
private ProcessResult processMessageSlice(final int start, final int end, final String folderName) throws Exception { logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName); final long startTime = System.currentTimeMillis(); final Store store = Session.getInstance(props).getStore(); store.connect(user, password); final Folder folder = store.getFolder(folderName); final UIDFolder uidfolder = (UIDFolder) folder; IMAPUtils.open(folder);/* w w w . java 2s . c om*/ try { final Message[] msgs = folder.getMessages(start, end); folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD); logger.debug("folder fetch done"); long highestUid = 0; int processedCount = 0; for (final Message m : msgs) { try { IMAPUtils.open(folder); final long uid = uidfolder.getUID(m); mailDestination.onMessage(m); highestUid = Math.max(highestUid, uid); processedCount++; if (Thread.currentThread().isInterrupted()) { break; } } catch (final Exception e) { stateManager.onError("Unable to make indexable message", m, e); logger.error("Unable to make indexable message due to {}", e, e.toString()); IMAPUtils.open(folder); } } final long endTime = System.currentTimeMillis() + 1; final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime); logger.debug("processMessageSlice() ended with " + pr); return pr; } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName); final Store store = Session.getInstance(props).getStore(); store.connect(user, password); try {/*from w w w . j a va2s .c om*/ for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists", fol); } else { logger.info( "Folder {} does not exist on the server, will remove it (and its content) also locally", fol); final RiverState riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(fol); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e); } } } } catch (final IndexMissingException ime) { logger.debug(ime.toString()); } catch (final Exception e) { logger.error("Error checking for stale folders", e); } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.info(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user); final Store store = Session.getInstance(props).getStore(); store.connect(user, password); if (deleteExpungedMessages) { try {// w w w . j a v a 2 s . c o m for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists for {}", fol, user); } else { logger.info( "Folder {} does not exist for {} on the server, will remove it (and its content) also locally", user, fol); final State riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(store.getFolder(fol)); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder for " + user, store.getFolder(fol), e); } } } } /*catch (final IndexMissingException ime) { logger.debug(ime.toString()); //TODO 2.0 check } */ catch (final Exception e) { logger.error("Error checking for stale folders", e); } } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java
/** * Process bounces./* w ww . j a va2 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:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java
protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession) throws MessagingException { String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME); String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME); if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) { mailService = getMailService();//from w w w .j a va2 s .c o m MessageActionPipe pipe = mailService.getPipe(PIPE_NAME); Visitor visitor = new Visitor(pipe); Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader()); // initialize context ExecutionContext initialExecutionContext = new ExecutionContext(); initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService()); initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString()); initialExecutionContext.put(CORE_SESSION_KEY, coreSession); initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol' // schema Folder rootFolder = null; Store store = null; try { String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME); initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType); // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY)); String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME); String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME); Boolean socketFactoryFallback = (Boolean) currentMailFolder .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME); String socketFactoryPort = (String) currentMailFolder .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME); Boolean starttlsEnable = (Boolean) currentMailFolder .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME); String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME); Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME); long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue(); String imapDebug = Framework.getProperty(IMAP_DEBUG, "false"); Properties properties = new Properties(); properties.put("mail.store.protocol", protocolType); // properties.put("mail.host", host); // Is IMAP connection if (IMAP.equals(protocolType)) { properties.put("mail.imap.host", host); properties.put("mail.imap.port", port); properties.put("mail.imap.starttls.enable", starttlsEnable.toString()); properties.put("mail.imap.debug", imapDebug); properties.put("mail.imap.partialfetch", "false"); } else if (IMAPS.equals(protocolType)) { properties.put("mail.imaps.host", host); properties.put("mail.imaps.port", port); properties.put("mail.imaps.starttls.enable", starttlsEnable.toString()); properties.put("mail.imaps.ssl.protocols", sslProtocols); properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.imaps.socketFactory.port", socketFactoryPort); properties.put("mail.imap.partialfetch", "false"); properties.put("mail.imaps.partialfetch", "false"); } else if (POP3S.equals(protocolType)) { properties.put("mail.pop3s.host", host); properties.put("mail.pop3s.port", port); properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.pop3s.socketFactory.port", socketFactoryPort); properties.put("mail.pop3s.ssl.protocols", sslProtocols); } else { // Is POP3 connection properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", port); } properties.put("user", email); properties.put("password", password); Session session = Session.getInstance(properties); store = session.getStore(); store.connect(email, password); String folderName = INBOX; // TODO should be an attribute in 'protocol' schema rootFolder = store.getFolder(folderName); // need RW access to update message flags rootFolder.open(Folder.READ_WRITE); Message[] allMessages = rootFolder.getMessages(); // VDU log.debug("nbr of messages in folder:" + allMessages.length); FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.FLAGS); fetchProfile.add(FetchProfile.Item.ENVELOPE); fetchProfile.add(FetchProfile.Item.CONTENT_INFO); fetchProfile.add("Message-ID"); fetchProfile.add("Content-Transfer-Encoding"); rootFolder.fetch(allMessages, fetchProfile); if (rootFolder instanceof IMAPFolder) { // ((IMAPFolder)rootFolder).doCommand(FetchProfile) } List<Message> unreadMessagesList = new ArrayList<Message>(); for (Message message : allMessages) { Flags flags = message.getFlags(); int unreadMessagesListSize = unreadMessagesList.size(); if (flags != null && !flags.contains(Flag.SEEN) && unreadMessagesListSize < emailsLimitLongValue) { unreadMessagesList.add(message); if (unreadMessagesListSize == emailsLimitLongValue - 1) { break; } } } Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]); // perform email import visitor.visit(unreadMessagesArray, initialExecutionContext); // perform flag update globally Flags flags = new Flags(); flags.add(Flag.SEEN); boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY); if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) { flags.add(Flag.SEEN); } else { flags.add(Flag.DELETED); } rootFolder.setFlags(unreadMessagesArray, flags, true); } finally { if (rootFolder != null && rootFolder.isOpen()) { rootFolder.close(true); } if (store != null) { store.close(); } } } }