List of usage examples for javax.mail Folder open
public abstract void open(int mode) throws MessagingException;
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public boolean deleteMessages(MailStoreConfiguration config, String[] uuids) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null; try {/*from w ww. j a v a2 s .c o m*/ // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); // Verify that we can even perform this operation if (!(inbox instanceof UIDFolder)) { String msg = "Delete feature is supported only for UIDFolder instances"; throw new UnsupportedOperationException(msg); } inbox.open(Folder.READ_WRITE); Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids)); inbox.setFlags(msgs, new Flags(Flag.DELETED), true); return true; // Indicate success } catch (MessagingException e) { log.error("Messaging exception while deleting messages", e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } return false; // We failed if we reached this point }
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * {@inheritDoc}/*from w w w. j a va 2 s . c om*/ * * @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.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public boolean setMessageReadStatus(MailStoreConfiguration config, String[] uuids, boolean read) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null; try {/* ww w.j av a 2s. c o m*/ // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); // Verify that we can even perform this operation log info if it isn't capable of operation if (!(inbox instanceof UIDFolder)) { String msg = "Toggle unread feature is supported only for UIDFolder instances"; log.info(msg); return false; } inbox.open(Folder.READ_WRITE); Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids)); inbox.setFlags(msgs, new Flags(Flag.SEEN), read); return true; // Indicate success } catch (MessagingException e) { log.error("Messaging exception while deleting messages", e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } return false; // We failed if we reached this point }
From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. */// w w w .jav a 2 s . c om protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * The main method of this job. Called by confluence every time the mail2news trigger * fires./*from w ww .j a va 2 s . c o m*/ * * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext) */ public void doExecute(JobExecutionContext arg0) throws JobExecutionException { /* The mailstore object used to connect to the server */ Store store = null; try { this.log.info("Executing mail2news plugin."); /* check if we have all necessary components */ if (pageManager == null) { throw new Exception("Null PageManager instance."); } if (spaceManager == null) { throw new Exception("Null SpaceManager instance."); } if (configurationManager == null) { throw new Exception("Null ConfigurationManager instance."); } /* get the mail configuration from the manager */ MailConfiguration config = configurationManager.getMailConfiguration(); if (config == null) { throw new Exception("Null MailConfiguration instance."); } /* create the properties for the session */ Properties prop = new Properties(); /* get the protocol to use */ if (config.getProtocol() == null) { throw new Exception("Cannot get protocol."); } String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : ""); /* assemble the property prefix for this protocol */ String propertyPrefix = "mail."; propertyPrefix = propertyPrefix.concat(protocol).concat("."); /* get the server port from the configuration and add it to the properties, * but only if it is actually set. If port = 0 this means we use the standard * port for the chosen protocol */ int port = config.getPort(); if (port != 0) { prop.setProperty(propertyPrefix.concat("port"), "" + port); } /* set connection timeout (10 seconds) */ prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000"); /* get the session for connecting to the mail server */ Session session = Session.getInstance(prop, null); /* get the mail store, using the desired protocol */ if (config.getSecure()) { store = session.getStore(protocol); } else { store = session.getStore(protocol); } /* get the host and credentials for the mail server from the configuration */ String host = config.getServer(); String username = config.getUsername(); String password = config.getPassword(); /* sanity check */ if (host == null || username == null || password == null) { throw new Exception("Incomplete mail configuration settings (at least one setting is null)."); } /* connect to the mailstore */ try { store.connect(host, username, password); } catch (AuthenticationFailedException afe) { throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe); } catch (MessagingException me) { throw new Exception("Connecting to mail store failed: " + me.getMessage(), me); } catch (IllegalStateException ise) { throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise); } catch (Exception e) { throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e); } /*** * Open the INBOX ***/ /* get the INBOX folder */ Folder folderInbox = store.getFolder("INBOX"); /* we need to open it READ_WRITE, because we want to move messages we already handled */ try { folderInbox.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open INBOX folder: " + e.getMessage(), e); } /* here we have to split, because IMAP will be handled differently from POP3 */ if (config.getProtocol().toLowerCase().equals("imap")) { /*** * Open the default folder, under which will be the processed * and the invalid folder. ***/ Folder folderDefault = null; try { folderDefault = store.getDefaultFolder(); } catch (MessagingException me) { throw new Exception("Could not get default folder: " + me.getMessage(), me); } /* sanity check */ try { if (!folderDefault.exists()) { throw new Exception( "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } catch (MessagingException me) { throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me); } /** * This is kind of a fallback mechanism. For some reasons it can happen that * the default folder has an empty name and exists() returns true, but when * trying to create a subfolder it generates an error message. * So what we do here is if the name of the default folder is empty, we * look for the "INBOX" folder, which has to exist and then create the * subfolders under this folder. */ if (folderDefault.getName().equals("")) { this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder."); folderDefault = store.getFolder("INBOX"); if (!folderDefault.exists()) { throw new Exception( "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } /*** * Open the folder for processed messages ***/ /* get the folder where we store processed messages */ Folder folderProcessed = folderDefault.getFolder("Processed"); /* check if it exists */ if (!folderProcessed.exists()) { /* does not exist, create it */ try { if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'processed' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderProcessed.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e); } /*** * Open the folder for invalid messages ***/ /* get the folder where we store invalid messages */ Folder folderInvalid = folderDefault.getFolder("Invalid"); /* check if it exists */ if (!folderInvalid.exists()) { /* does not exist, create it */ try { if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'invalid' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderInvalid.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e); } /*** * Get all new messages ***/ /* get all messages in the INBOX */ Message message[] = folderInbox.getMessages(); /* go through all messages and get the unseen ones (all should be unseen, * as the seen ones get moved to a different folder */ for (int i = 0; i < message.length; i++) { if (message[i].isSet(Flags.Flag.SEEN)) { /* this message has been seen, should not happen */ /* send email to the sender */ sendErrorMessage(message[i], "This message has already been flagged as seen before being handled and was thus ignored."); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart) content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* move the message to the processed folder */ moveMessage(message[i], folderInbox, folderProcessed); } /* close the folders, expunging deleted messages in the process */ folderInbox.close(true); folderProcessed.close(true); folderInvalid.close(true); /* close the store */ store.close(); } else if (config.getProtocol().toLowerCase().equals("pop3")) { /* get all messages in this POP3 account */ Message message[] = folderInbox.getMessages(); /* go through all messages */ for (int i = 0; i < message.length; i++) { Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart) content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to the sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* finished processing this message, delete it */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ } /* close the pop3 folder, deleting all messages flagged as DELETED */ folderInbox.close(true); /* close the mail store */ store.close(); } else { throw new Exception("Unknown protocol: " + config.getProtocol()); } } catch (Exception e) { /* catch any exception which was not handled so far */ this.log.error("Error while executing mail2news job: " + e.getMessage(), e); JobExecutionException jee = new JobExecutionException( "Error while executing mail2news job: " + e.getMessage(), e, false); throw jee; } finally { /* try to do some cleanup */ try { store.close(); } catch (Exception e) { } } }
From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java
/** * Ingests email from a mailbox.//from w ww . java 2 s . com */ public void execute() { // get message store Store store; try { long startTime = System.nanoTime(); store = storeFactory.getStore(); log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime); } catch (MessagingException ex) { log.error("Error getting message store.", ex); return; } try { // get folders Folder inputFolder = store.getFolder(inputFolderName); if (!inputFolder.exists()) { log.error("Input folder {} does not exist.", inputFolderName); return; } Folder successFolder = null; if (StringUtils.isNotBlank(successFolderName)) { successFolder = store.getFolder(successFolderName); if (!successFolder.exists()) { log.error("Success folder {} does not exist.", successFolderName); return; } } Folder discardFolder = null; if (StringUtils.isNotBlank(discardFolderName)) { discardFolder = store.getFolder(discardFolderName); if (!discardFolder.exists()) { log.error("Discard folder {} does not exist.", discardFolderName); return; } } Folder errorFolder = null; if (StringUtils.isNotBlank(errorFolderName)) { errorFolder = store.getFolder(errorFolderName); if (!errorFolder.exists()) { log.error("Error folder {} does not exist.", errorFolderName); return; } } inputFolder.open(Folder.READ_WRITE); // fetch messages // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE) // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached // body structure and thought that the content itself was cached, but I'd think a bug like that would have // been found by many people and fixed long ago, so I'm assuming it's something else.) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inputFolder.getMessages(); inputFolder.fetch(msgs, fp); log.debug("About to process {} messages", msgs.length); // process each message if (msgs.length > 0) { List<Message> successMessages = new ArrayList<Message>(); List<Message> errorMessages = new ArrayList<Message>(); List<Message> discardMessages = new ArrayList<Message>(); List<Message> responseMessages = new ArrayList<Message>(); for (int i = 0; i < msgs.length; i++) { Message message = msgs[i]; try { boolean processed = messageProcessor.execute(message, responseMessages); (processed ? successMessages : discardMessages).add(message); } catch (Exception ex) { log.error("Failed to process email message.", ex); errorMessages.add(message); } } // send response messages for (Message responseMessage : responseMessages) { emailerFactory.sendMail(responseMessage); } // move and purge messages if (successFolder != null && !successMessages.isEmpty()) { inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]), successFolder); } if (discardFolder != null && !discardMessages.isEmpty()) { inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]), discardFolder); } if (errorFolder != null && !errorMessages.isEmpty()) { inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder); } for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flag.DELETED, true); } log.info("{} messages processed: {} successful, {} discarded, {} failed.", new Object[] { msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() }); } // close folder inputFolder.close(true); } catch (MessagingException ex) { log.error("Error ingesting email.", ex); } catch (Exception ex) { log.error("Error ingesting email.", ex); } finally { // close store try { store.close(); } catch (MessagingException ex) { log.error("Error closing message store.", ex); } } }
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing */// ww w .j a v a 2 s .com public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * Opens a folder and print all msgs found. * @param folder//from w ww . j ava2 s . co m * @param userId * @param pwd */ void printAllMsgs(String folderName, String userId, String pwd) throws MessagingException { IMAPSSLStore sslStore = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); String[] access = new String[2]; access[0] = userId; access[1] = pwd; Folder folder = getImapFolder(session, sslStore, access, folderName); folder.open(Folder.READ_WRITE); try { this.printAllMsgs(folder.getMessages()); } catch (MessagingException ex) { System.out.println("ERROR at printAllEmailMsgs."); } }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
private SetMessageResponseType saveDraft(SetMessageRequestType request, String[] access, IMAPSSLStore sslStore, String destinationFolder, Session session) throws MessagingException { SetMessageResponseType response = new SetMessageResponseType(); Folder folder = getImapFolder(session, sslStore, access, destinationFolder); folder.open(Folder.READ_WRITE); IMAPMessage imapMessage = null;//from w w w.j a v a 2s. co m Message[] msgArr = null; try { msgArr = createMessage(session, access[0], request); folder.appendMessages(msgArr); } catch (Exception e) { log.error("Error creating draft message"); response.setSuccessStatus(false); response.setMessage("Error saving draft message for user = " + request.getUserId()); e.printStackTrace(); return response; } response.setSuccessStatus(true); response.setMessage(" "); return response; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Expunge all folders that have messages waiting to be deleted *///from ww w .java 2s . c o m 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); } } } } }