List of usage examples for javax.mail Folder READ_WRITE
int READ_WRITE
To view the source code for javax.mail Folder READ_WRITE.
Click Source Link
From source file:com.zotoh.maedr.device.PopIO.java
private void openFolder() throws Exception { if (_fd != null && !_fd.isOpen()) { _fd.open(Folder.READ_WRITE); } }
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);//from w w w . j a v a 2s . co m checkStoreForTestConnection(store); 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.syncope.core.logic.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) throws Exception { LOG.info("Waiting for notification to be sent..."); try {//from w ww.j a va 2 s .c o m Thread.sleep(1000); } catch (InterruptedException e) { } boolean found = false; Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(POP3_HOST, POP3_PORT, MAIL_ADDRESS, MAIL_PASSWORD); Folder inbox = store.getFolder("INBOX"); assertNotNull(inbox); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) { found = true; messages[i].setFlag(Flag.DELETED, true); } } inbox.close(true); store.close(); return found; }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
/** * {@inheritDoc}/*from w w w. j ava 2 s .co m*/ */ @Override public SampleResult sample(Entry e) { SampleResult parent = new SampleResult(); boolean isOK = false; // Did sample succeed? final boolean deleteMessages = getDeleteMessages(); final String serverProtocol = getServerType(); parent.setSampleLabel(getName()); String samplerString = toString(); parent.setSamplerData(samplerString); /* * Perform the sampling */ parent.sampleStart(); // Start timing try { // Create empty properties Properties props = new Properties(); if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$ if (isEnforceStartTLS()) { // Requires JavaMail 1.4.2+ props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$ } } if (isTrustAllCerts()) { if (isUseSSL()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } else if (isUseLocalTrustStore()) { File truststore = new File(getTrustStoreToUse()); log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse()); log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (isUseSSL()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } // Get session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(serverProtocol); store.connect(getServer(), getPortAsInt(), getUserName(), getPassword()); // Get folder Folder folder = store.getFolder(getFolder()); if (deleteMessages) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } final int messageTotal = folder.getMessageCount(); int n = getNumMessages(); if (n == ALL_MESSAGES || n > messageTotal) { n = messageTotal; } // Get directory Message[] messages = folder.getMessages(1, n); StringBuilder pdata = new StringBuilder(); pdata.append(messages.length); pdata.append(" messages found\n"); parent.setResponseData(pdata.toString(), null); parent.setDataType(SampleResult.TEXT); parent.setContentType("text/plain"); // $NON-NLS-1$ final boolean headerOnly = getHeaderOnly(); busy = true; for (Message message : messages) { StringBuilder cdata = new StringBuilder(); SampleResult child = new SampleResult(); child.sampleStart(); cdata.append("Message "); // $NON-NLS-1$ cdata.append(message.getMessageNumber()); child.setSampleLabel(cdata.toString()); child.setSamplerData(cdata.toString()); cdata.setLength(0); final String contentType = message.getContentType(); child.setContentType(contentType);// Store the content-type child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default child.setEncodingAndType(contentType);// Parse the content-type if (isStoreMimeMessage()) { // Don't save headers - they are already in the raw message ByteArrayOutputStream bout = new ByteArrayOutputStream(); message.writeTo(bout); child.setResponseData(bout.toByteArray()); // Save raw message child.setDataType(SampleResult.TEXT); } else { @SuppressWarnings("unchecked") // Javadoc for the API says this is OK Enumeration<Header> hdrs = message.getAllHeaders(); while (hdrs.hasMoreElements()) { Header hdr = hdrs.nextElement(); String value = hdr.getValue(); try { value = MimeUtility.decodeText(value); } catch (UnsupportedEncodingException uce) { // ignored } cdata.append(hdr.getName()).append(": ").append(value).append("\n"); } child.setResponseHeaders(cdata.toString()); cdata.setLength(0); if (!headerOnly) { appendMessageData(child, message); } } if (deleteMessages) { message.setFlag(Flags.Flag.DELETED, true); } child.setResponseOK(); if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called. child.sampleEnd(); } parent.addSubResult(child); } // Close connection folder.close(true); store.close(); parent.setResponseCodeOK(); parent.setResponseMessageOK(); isOK = true; } catch (NoClassDefFoundError | IOException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString()); } catch (MessagingException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$ } finally { busy = false; } if (parent.getEndTime() == 0) {// not been set by any child samples parent.sampleEnd(); } parent.setSuccessful(isOK); return parent; }
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 ava 2 s. c om 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(); } } } }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method delete all the sent mails. Can be used after a particular test class * * @throws MessagingException//from w ww. j a v a 2s .c om * @throws IOException */ public static void deleteSentMails() throws MessagingException, IOException { Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder sentMail = store.getFolder("[Gmail]/Sent Mail"); sentMail.open(Folder.READ_WRITE); Message[] messages = sentMail.getMessages(); Flags deleted = new Flags(Flags.Flag.DELETED); sentMail.setFlags(messages, deleted, true); sentMail.close(true); 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);/* ww w.j ava2 s. c o m*/ checkStoreForTestConnection(store); 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:com.liferay.mail.imap.IMAPAccessor.java
public Folder openFolder(Folder jxFolder) throws MailException { try {//from w w w.ja v a 2 s . c om if (jxFolder.isOpen()) { return jxFolder; } jxFolder.open(Folder.READ_WRITE); return jxFolder; } catch (MessagingException me) { throw new MailException(me); } }
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 . java2 s .c om*/ * * @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.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public EmailMessage getMessage(MailStoreConfiguration config, String messageId) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null;//from w w w.j av a 2 s . c o m try { int mode = config.getMarkMessagesAsRead() ? Folder.READ_WRITE : Folder.READ_ONLY; // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); inbox.open(mode); Message message; if (inbox instanceof UIDFolder) { message = ((UIDFolder) inbox).getMessageByUID(Long.parseLong(messageId)); } else { message = inbox.getMessage(Integer.parseInt(messageId)); } boolean unread = !message.isSet(Flags.Flag.SEEN); if (config.getMarkMessagesAsRead()) { message.setFlag(Flag.SEEN, true); } EmailMessage emailMessage = wrapMessage(message, true, session); if (!config.getMarkMessagesAsRead()) { // NOTE: This is more than a little bit annoying. Apparently // the mere act of accessing the body content of a message in // Javamail flags the in-memory representation of that message // as SEEN. It does *nothing* to the mail server (the message // is still unread in the SOR), but it wreaks havoc on local // functions that key off that value and expect it to be // accurate. We're obligated, therefore, to restore the value // to what it was before the call to wrapMessage(). emailMessage.setUnread(unread); } return emailMessage; } catch (MessagingException e) { log.error("Messaging exception while retrieving individual message", e); } catch (IOException e) { log.error("IO exception while retrieving individual message", e); } catch (ScanException e) { log.error("AntiSamy scanning exception while retrieving individual message", e); } catch (PolicyException e) { log.error("AntiSamy policy exception while retrieving individual message", 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 null; }