List of usage examples for javax.mail Folder close
public abstract void close(boolean expunge) throws MessagingException;
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. ja v a2s . 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:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException { folder.open(Folder.READ_ONLY);/*from w w w. j a v a 2 s.c om*/ String folderFullName = folder.getFullName(); try { int max = folder.getMessageCount(); int i = 0; final int buffer = item.getBufferSize(); while (i < max && !thread.isAborted()) { thread.setStatusInfo(CrawlStatus.CRAWL); int end = i + buffer; if (end > max) end = max; Message[] messages = folder.getMessages(i + 1, end); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, fp); for (Message message : messages) { if (thread.isAborted()) break; i++; String messageId = getMessageId(folder, message); if (StringUtils.isEmpty(messageId)) continue; if (thread.isAlreadyIndexed(messageId)) { thread.incIgnored(); continue; } IndexDocument crawlIndexDocument = new IndexDocument(item.getLang()); IndexDocument parserIndexDocument = new IndexDocument(item.getLang()); crawlIndexDocument.addString(MailboxFieldEnum.folder.name(), folderFullName); try { readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId); thread.addDocument(crawlIndexDocument, parserIndexDocument); } catch (Exception e) { Logging.warn(e); thread.incError(); } } } } finally { folder.close(false); } }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *///from ww w . j a v a 2 s.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:net.wastl.webmail.server.WebMailSession.java
public void removeFolder(String id, boolean recurse) throws MessagingException { Folder folder = getFolder(id); if (folder.isOpen()) folder.close(false); folder.delete(recurse);// w w w . jav a 2s . co m // Should be called from FolderSetup Plugin //refreshFolderInformation(); }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
private void updateImapSSLMail(SetMessageRequestType request, Folder folder, IMAPMessage message) throws MessagingException { // folder.open(Folder.READ_WRITE); List<String> labelList = request.getLabels(); if (!labelList.isEmpty() && labelList.get(0).equalsIgnoreCase("starred")) { message.setFlag(Flags.Flag.FLAGGED, true); } else {//from www . j a va 2s.co m message.setFlag(Flags.Flag.FLAGGED, false); } if (request.getAction().equalsIgnoreCase("Read")) { message.setFlag(Flags.Flag.SEEN, true); } // message.saveChanges(); folder.close(false); }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Disconnect from mailhost "name"// w w w . j ava2 s. c om */ public void disconnect(String name) { try { Folder f = connections.get(name); if (f != null && f.isOpen()) { f.close(true); Store st = connections.get(name).getStore(); //st.close(); log.info("Mail: Disconnected from folder " + f.toString() + " at store " + st.toString() + "."); } else { log.warn("Mail: Folder " + name + " was null???."); } } catch (MessagingException ex) { // Should not happen log.fatal("Unexpected failure to disconnect", ex); } catch (NullPointerException ex) { // This happens when deleting a folder with an error log.fatal("Failed to disconnect after deleting folder? " + ex); // Log exception too if the comment above is wrong } finally { connections.remove(name); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Expunge all folders that have messages waiting to be deleted *///from w w w. j a v a 2 s . c om public void expungeFolders() { if (need_expunge_folders != null) { Enumeration<String> enumVar = need_expunge_folders.elements(); while (enumVar.hasMoreElements()) { String hash = (String) enumVar.nextElement(); if (user.wantsSetFlags()) { Folder f = getFolder(hash); try { if (f.isOpen()) { f.close(false); } f.open(Folder.READ_WRITE); // POP3 doesn't support expunge! try { f.expunge(); } catch (MessagingException ex) { } f.close(true); } catch (MessagingException ex) { // XXXX log.error("Failed to expunge folders", ex); } } } } }
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.//from w w w . ja va 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:net.wastl.webmail.server.WebMailSession.java
/** * Copy or move the selected messages from folder fromfolder to folder tofolder. */// w w w. j a v a 2 s . com public void copyMoveMessage(String fromfolder, String tofolder, HTTPRequestHeader head, boolean move) throws MessagingException { Folder from = getFolder(fromfolder); Folder to = getFolder(tofolder); if (user.wantsSetFlags()) { if (from.isOpen() && from.getMode() == Folder.READ_ONLY) { from.close(false); from.open(Folder.READ_WRITE); } else if (!from.isOpen()) { from.open(Folder.READ_WRITE); } if (to.isOpen() && to.getMode() == Folder.READ_ONLY) { to.close(false); to.open(Folder.READ_WRITE); } else if (!to.isOpen()) { to.open(Folder.READ_WRITE); } } else { if (!from.isOpen()) { from.open(Folder.READ_ONLY); } if (to.isOpen() && to.getMode() == Folder.READ_ONLY) { to.close(false); to.open(Folder.READ_WRITE); } else if (!to.isOpen()) { to.open(Folder.READ_WRITE); } } int m[] = getSelectedMessages(head, from.getMessageCount()); Message msgs[] = from.getMessages(m); from.copyMessages(msgs, to); if (move && user.wantsSetFlags()) { from.setFlags(m, new Flags(Flags.Flag.DELETED), true); if (user.getBoolVar("autoexpunge")) { from.close(true); to.close(true); } else { if (need_expunge_folders == null) { need_expunge_folders = new Vector<String>(); } need_expunge_folders.addElement(fromfolder); from.close(false); to.close(false); } } else { from.close(false); if (user.getBoolVar("autoexpunge")) { to.close(true); } else { to.close(false); } } from.open(Folder.READ_WRITE); to.open(Folder.READ_WRITE); refreshFolderInformation(fromfolder); refreshFolderInformation(tofolder); }
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * {@inheritDoc}/* w w w . j ava2 s . 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); } } } }