Example usage for javax.mail Store close

List of usage examples for javax.mail Store close

Introduction

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

Prototype

public synchronized void close() throws MessagingException 

Source Link

Document

Close this service and terminate its connection.

Usage

From source file:org.campware.dream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    String host = TurbineResources.getString("mail.pop3.host");
    String username = TurbineResources.getString("mail.pop3.user");
    String password = TurbineResources.getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//from w  ww  . ja  v  a 2s .c o m

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    // Process each message
    //
    Address fromAddress = new InternetAddress();
    String from = new String();
    String name = new String();
    String email = new String();
    String subject = new String();
    String content = new String();
    for (int i = 0; i < messages.length; i++) {
        email = ((InternetAddress) messages[i].getFrom()[0]).getAddress();
        name = ((InternetAddress) messages[i].getFrom()[0]).getPersonal();
        subject = messages[i].getSubject();
        content = messages[i].getContent().toString();

        DinboxEvent entry = new DinboxEvent();

        Criteria criteria = new Criteria();
        criteria.add(DistributorPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (DistributorPeer.doSelect(criteria).size() > 0) {
            Distributor myDistrib = (Distributor) DistributorPeer.doSelect(criteria).get(0);
            entry.setDistributorId(myDistrib.getDistributorId());
        } else {
            if (name != null) {
                entry.setBody("From: " + name + " " + email + "\n\n" + content);
            } else {
                entry.setBody("From: " + email + "\n\n" + content);
            }
        }

        entry.setDinboxEventCode(getTempCode());

        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setSubject(subject);

        entry.setIssuedDate(new Date());
        entry.setCreatedBy("scheduler");
        entry.setCreated(new Date());
        entry.setModifiedBy("scheduler");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(DinboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setDinboxEventCode(getRowCode("IE", entry.getDinboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;

        } finally {
            if (!success)
                Transaction.safeRollback(conn);
        }

        messages[i].setFlag(Flags.Flag.DELETED, true);
    }

    // Close connection 
    folder.close(true);
    store.close();

}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testEightBitMessage() throws Exception {

    Store lstore = session.getStore(PROTOCOL);
    lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD);

    String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME;

    IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName);
    lfolder.open(Folder.READ_WRITE);//from   w  ww .  j a  v  a  2 s.c o  m

    InputStream messageFileInputStream1 = null;
    InputStream messageFileInputStream2 = null;
    try {
        ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml");
        messageFileInputStream1 = new FileInputStream(fileResource.getFile());
        Message message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                messageFileInputStream1);
        String subject = message.getSubject();

        // get original bytes for further comparation
        messageFileInputStream2 = new FileInputStream(fileResource.getFile());
        byte[] original = ASCIIUtility.getBytes(messageFileInputStream2);

        Message[] messages = { message };

        lfolder.appendMessages(messages);

        // The search is not implemented. 
        // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit");
        // messages = folder.search(term);

        // So wee need to get our test message's UID from the repo

        String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":"
                + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]";

        QueryParameterDefinition[] params = new QueryParameterDefinition[1];
        params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE,
                serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject);

        List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params,
                namespaceService, true);

        // does the message exist
        assertEquals(1, nodeRefs.size());

        NodeRef messageNodeRef = nodeRefs.get(0);

        // get message UID
        Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID);

        // fetch the massage
        RFC822DATA data = getRFC822Message(lfolder, dbid);

        assertNotNull("Can't fetch a message from the repositiry", data);

        byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream());

        assertTrue("Original message doesn't coincide to the message processed by the repository",
                Arrays.equals(original, processed));
    } finally {
        if (messageFileInputStream1 != null)
            messageFileInputStream1.close();
        if (messageFileInputStream2 != null)
            messageFileInputStream2.close();
    }

    // close connection
    lfolder.close(true);
    lstore.close();

}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index the given Collection.//from w w  w .  j a va 2s .  co  m
 * 
 * @param fullIndex indicates whether a full or incremental index should be created
 * @throws IndexException if the Collections can not be indexed
 * @return true if succesfull
 */
private final boolean doIndex(boolean fullIndex) throws IndexException {
    IndexWriter writer = null;
    Store store = null;
    try {
        // record start time
        StopWatch watch = new StopWatch();

        watch.start();

        // make sure the index exists
        File indexDirectory = this.getIndexDirWithManagerDefaults();

        // reindex if the index is not there or invalid
        boolean mustReindex = fullIndex;
        if (!this.isIndexValid()) {
            mustReindex = true;
            indexDirectory.mkdirs();
        }

        // create an index(writer)
        writer = new IndexWriter(indexDirectory, this.createAnalyzer(), mustReindex);
        // see whether there are specific indexing settings in manager
        if (manager.getMergeFactor() != null) {
            writer.setMergeFactor(manager.getMergeFactor().intValue());
        }
        if (manager.getMinMergeDocs() != null) {
            writer.setMaxBufferedDocs(manager.getMinMergeDocs().intValue());
        }

        if (manager.getMaxMergeDocs() != null) {
            writer.setMaxMergeDocs(manager.getMaxMergeDocs().intValue());
        }

        resetCache(fullIndex);
        // connect to IMAP
        log.debug("Connecting to IMAP server: " + host);
        Properties props = System.getProperties();
        Session session = Session.getDefaultInstance(props, null);
        store = session.getStore("imap");
        log.debug("Connecting to " + host + " as " + user);
        store.connect(host, user, password);
        log.debug("Connected");
        // start at the proper folder
        Folder topFolder = null;
        if (StringUtils.hasText(folder)) {
            topFolder = store.getFolder(folder);
        } else {
            topFolder = store.getDefaultFolder();
        }
        indexFolder(writer, topFolder);
        // record end time and report duration of indexing
        watch.stop();
        log.info("Indexed " + writer.docCount() + " documents in " + watch.elapsedTime());
        return true;
    } catch (NoSuchProviderException e) {
        throw new IndexException("Can't connect to " + host, e);
    } catch (MessagingException e) {
        throw new IndexException("Error while accessing IMAP server " + host, e);
    } catch (IOException e) {
        throw new IndexException("Error indexing '" + this.getName() + "'. Possibly unable to remove old index",
                e);
    } catch (Exception e) {
        throw new IndexException("Error indexing '" + this.getName() + "'", e);
    } finally {
        if (writer != null) {
            try {
                writer.optimize();
                log.debug("Optimizing index for " + name);
                writer.close();
                log.debug("Closing index for " + name);
            } catch (IOException e1) {
                log.error("Error closing Index for " + name, e1);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e1) {
                log.error("Error closing IMAP server " + host, e1);
            }
        }
        init();
    }
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*from   w  w w  .j  ava2 s.  c  o  m*/
    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_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // 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 address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        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:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java

/**
 * Loads email properties, reads email messages, 
 * converts their multipart bodies into string,
 * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports
 * <p><b> deletes messages//  w  w w .  java  2 s.c om
 * @see #readEmail()
 * @see #convertToXml(HashSet)
 * @see ru.retbansk.utils.scheduled.ReplyManager
 * @return HashSet<DayReport> of the Valid Day Reports
 */
@Override
public HashSet<DayReport> readEmail() throws Exception {

    Properties prop = loadProperties();
    String host = prop.getProperty("host");
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    path = prop.getProperty("path");

    // Get system properties
    Properties properties = System.getProperties();

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    // Get a Store object that implements the specified protocol.
    Store store = session.getStore("pop3");

    // Connect to the current host using the specified username and
    // password.
    store.connect(host, user, password);

    // Create a Folder object corresponding to the given name.
    Folder folder = store.getFolder("inbox");

    // Open the Folder.
    folder.open(Folder.READ_WRITE);
    HashSet<DayReport> dayReportSet = new HashSet<DayReport>();
    try {

        // Getting messages from the folder
        Message[] message = folder.getMessages();
        // Reversing the order in the array with the use of Set to make the last one final
        Collections.reverse(Arrays.asList(message));

        // Reading messages.
        String body;
        for (int i = 0; i < message.length; i++) {
            DayReport dayReport = null;
            dayReport = new DayReport();
            dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
            calendar.setTime(message[i].getSentDate());
            dayReport.setCalendar(calendar);
            dayReport.setSubject(message[i].getSubject());
            List<TaskReport> reportList = null;

            //Release the string from email message body
            body = "";
            Object content = message[i].getContent();
            if (content instanceof java.lang.String) {
                body = (String) content;
            } else if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;

                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);

                    String disposition = part.getDisposition();

                    if (disposition == null) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    } else if ((disposition != null)
                            && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    }
                }
            }

            //Put the string (body of email message) and get list of valid reports else send error
            reportList = new ArrayList<TaskReport>();
            reportList = giveValidReports(body, message[i].getSentDate());
            //Check for valid day report. To be valid it should have size of reportList > 0.
            if (reportList.size() > 0) {
                // adding valid ones to Set
                dayReport.setReportList(reportList);
                dayReportSet.add(dayReport);
            } else {
                // This message doesn't have valid reports. Sending an error reply.
                logger.info("Invalid Day Report detected. Sending an error reply");
                ReplyManager man = new ReplyManagerSimpleImpl();
                man.sendError(dayReport);
            }
            // Delete message
            message[i].setFlag(Flags.Flag.DELETED, true);
        }

    } finally {
        // true tells the mail server to expunge deleted messages.
        folder.close(true);
        store.close();
    }

    return dayReportSet;
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}/*w w w  .j  a  va  2  s.  c o 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.eurekastreams.server.service.email.ImapEmailIngester.java

/**
 * Ingests email from a mailbox.//from w w  w .  j av  a  2s . co  m
 */
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:org.nuclos.server.ruleengine.RuleInterface.java

/**
 *
 * @param pop3Host//from w w  w. j av a2  s.c o  m
 * @param pop3Port
 * @param pop3User
 * @param pop3Password
 * @param remove
 * @return
 * @throws NuclosFatalRuleException
 */
public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User,
        final String pop3Password, boolean remove) throws NuclosFatalRuleException {
    try {
        Properties properties = new Properties();
        properties.setProperty("mail.pop3.host", pop3Host);
        properties.setProperty("mail.pop3.port", pop3Port);
        properties.setProperty("mail.pop3.auth", "true");
        properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(pop3User, pop3Password);
            }
        });

        session.setDebug(true);
        Store store = session.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        if (remove) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        List<NuclosMail> result = new ArrayList<NuclosMail>();

        Message message[] = folder.getMessages();
        for (int i = 0; i < message.length; i++) {
            Message m = message[i];
            NuclosMail mail = new NuclosMail();
            logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: "
                    + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType()
                    + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate());

            Address[] senders = m.getFrom();
            if (senders.length == 1 && senders[0] instanceof InternetAddress) {
                mail.setFrom(((InternetAddress) senders[0]).getAddress());
            } else {
                mail.setFrom(Arrays.toString(m.getFrom()));
            }
            mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO)));
            mail.setSubject(m.getSubject());

            if (m.isMimeType("text/plain")) {
                mail.setMessage((String) m.getContent());
            } else {
                Multipart mp = (Multipart) m.getContent();
                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);
                    String disposition = part.getDisposition();
                    MimeBodyPart mimePart = (MimeBodyPart) part;
                    logger.debug(
                            "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

                    if (disposition == null
                            && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) {
                        mail.setMessage((String) mimePart.getDataHandler().getContent());
                    }
                }
                getAttachments(mp, mail);
            }

            result.add(mail);

            if (remove) {
                m.setFlag(Flags.Flag.DELETED, true);
            }
        }

        if (remove) {
            folder.close(true);
        } else {
            folder.close(false);
        }

        store.close();

        return result;
    } catch (Exception e) {
        throw new NuclosFatalRuleException(e);
    }
}

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();//w ww  .  j  a v a 2s.  co 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();
            }
        }
    }
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//from   w  w w . j  a v  a  2  s  . co  m

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    for (int i = 0; i < messages.length; i++) {

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}