Example usage for javax.mail Message getContent

List of usage examples for javax.mail Message getContent

Introduction

In this page you can find the example usage for javax.mail Message getContent.

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

private Object getMessage(String requestMsgId) {
    Session session = Session.getInstance(props, null);
    session.setDebug(log.isTraceEnabled());
    Store store = null;/*from   w w w.  java2 s  .  co  m*/

    try {
        store = session.getStore("pop3");
        store.connect(username, password);
        Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
        folder.open(Folder.READ_WRITE);
        Message[] msgs = folder.getMessages();
        log.debug(msgs.length + " replies in reply mailbox");
        for (Message m : msgs) {
            String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
            log.debug("Got reply to : " + Arrays.toString(inReplyTo));
            if (inReplyTo != null && inReplyTo.length > 0) {
                for (int j = 0; j < inReplyTo.length; j++) {
                    if (requestMsgId.equals(inReplyTo[j])) {
                        m.setFlag(Flags.Flag.DELETED, true);
                        return m.getContent();
                    }
                }
            }
            m.setFlag(Flags.Flag.DELETED, true);
        }
        folder.close(true);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException ignore) {
            }
            store = null;
        }
    }
    return null;
}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * //from   ww w  .  j av a 2s .c o m
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder/* ww w  .  j a  v a 2 s . com*/
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

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

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);//from  w  ww  .j  a va 2  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_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **///w  ww  .j av a2  s .  c o m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java

@Test
public void testSendMessage() throws MessagingException, IOException {
    bean.sendMessage(TEST_TO_ADDRESS, TEST_CC_ADDRESSES, TEST_BOUNCE_ADDRESS, testMessage);
    Message message = mailbox.get(0);
    InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
    assertEquals(TEST_FROM_ADDRESS, fromAddress.getAddress());
    assertEquals(TEST_FROM_NAME, fromAddress.getPersonal());
    InternetAddress toAddress = (InternetAddress) message.getRecipients(RecipientType.TO)[0];
    assertEquals(TEST_TO_ADDRESS, toAddress.getAddress());
    assertEquals(2, message.getRecipients(RecipientType.CC).length);
    InternetAddress ccAddress1 = (InternetAddress) message.getRecipients(RecipientType.CC)[0];
    InternetAddress ccAddress2 = (InternetAddress) message.getRecipients(RecipientType.CC)[1];
    assertEquals(TEST_CC_ADDRESSES.get(0), ccAddress1.getAddress());
    assertEquals(TEST_CC_ADDRESSES.get(1), ccAddress2.getAddress());
    assertEquals(TEST_SUBJECT, message.getSubject());
    assertEquals(TEST_CONTENT, message.getContent());
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * Retrieve attachment from message id/*from  ww w  .ja  v a2  s . co  m*/
 * 
 * @param mid
 * @return
 */
public FileUtil getAttachment(int mid) {

    FileUtil file = null;
    if (store == null)
        return file;

    try {
        /*
         * Connect to IMAP store
         */
        store.connect();

        /*
         * Retrieve & open INBOX folder
         */
        Folder folder = store.getFolder(ImapConstants.INBOX);
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        Message m = null;

        /* 
         * Message message = folder.getMessage(mid); 
         * 
         * the method 'getMessage' always returns an
         * index out of bound error, so we have to
         * introduce the hack below
         */

        for (int i = 0; i < messages.length; i++) {
            if (i == mid)
                m = messages[i];
        }

        if (m == null)
            return file;

        Object content = m.getContent();
        if (content instanceof Multipart) {
            file = handleMultipart((Multipart) content, true);

        } else {
            file = handlePart(m, true);

        }

        folder.close(false);
        store.close();

    } catch (Exception e) {
        e.printStackTrace();

    }

    return file;

}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);/* www .  j a v a2  s  .co m*/
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from w  w  w .  j av a  2 s  . c o  m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:org.accesointeligente.server.robots.ResponseChecker.java

public void connectAndCheck() {
    if (ApplicationProperties.getProperty("email.server") == null
            || ApplicationProperties.getProperty("email.user") == null
            || ApplicationProperties.getProperty("email.password") == null
            || ApplicationProperties.getProperty("email.folder") == null
            || ApplicationProperties.getProperty("email.failfolder") == null
            || ApplicationProperties.getProperty("attachment.directory") == null
            || ApplicationProperties.getProperty("attachment.baseurl") == null) {
        logger.error("Properties are not defined!");
        return;/*from w  ww  .ja v  a2s.  c  o m*/
    }

    org.hibernate.Session hibernate = null;

    try {
        session = Session.getInstance(props, null);
        store = session.getStore("imaps");
        store.connect(ApplicationProperties.getProperty("email.server"),
                ApplicationProperties.getProperty("email.user"),
                ApplicationProperties.getProperty("email.password"));

        Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder"));
        Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder"));
        inbox.open(Folder.READ_WRITE);

        for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) {
            try {
                logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject());
                remoteIdentifiers = null;
                messageBody = null;
                remoteIdentifiers = new HashSet<String>();

                if (message.getSubject() != null) {
                    Matcher matcher = pattern.matcher(message.getSubject());

                    if (matcher.matches()) {
                        remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                        logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                    }
                }

                Object content = message.getContent();

                if (content instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    logger.info("Email content type is Multipart, each part of " + mp.getCount()
                            + " will be processed");

                    for (int i = 0, n = mp.getCount(); i < n; i++) {
                        Part part = mp.getBodyPart(i);
                        logger.info("Part: " + (i + 1) + " of " + mp.getCount());
                        processPart(part);
                    }
                } else if (content instanceof String) {
                    logger.info("Email content type is String");
                    messageBody = (String) content;
                    Matcher matcher;
                    StringTokenizer tokenizer = new StringTokenizer(messageBody);

                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        matcher = pattern.matcher(token);

                        if (matcher.matches()) {
                            remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                    Integer.parseInt(matcher.group(3))));
                            logger.info("remote identifier: " + formatIdentifier(matcher.group(1),
                                    matcher.group(2), Integer.parseInt(matcher.group(3))));
                        }
                    }
                } else {
                    logger.info("Email content type isn't String or Multipart");
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                    continue;
                }

                Boolean requestFound = false;
                Matcher matcher = htmlPattern.matcher(messageBody);

                if (matcher.find()) {
                    messageBody = htmlToString(messageBody);
                }

                logger.info("Searching for Request Remote Identifier");
                for (String remoteIdentifier : remoteIdentifiers) {
                    hibernate = HibernateUtil.getSession();
                    hibernate.beginTransaction();

                    Criteria criteria = hibernate.createCriteria(Request.class);
                    criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier));
                    Request request = (Request) criteria.uniqueResult();
                    hibernate.getTransaction().commit();

                    if (request != null) {
                        logger.info("Request found for Remote Identifier: " + remoteIdentifier);
                        Response response;

                        // If the attachments haven't been used, use them. Otherwise, copy them.
                        if (!requestFound) {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        } else {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        }

                        hibernate = HibernateUtil.getSession();
                        hibernate.beginTransaction();

                        response.setRequest(request);
                        request.setStatus(RequestStatus.RESPONDED);
                        request.setExpired(RequestExpireType.WITHRESPONSE);
                        request.setResponseDate(new Date());
                        hibernate.update(request);
                        hibernate.update(response);
                        hibernate.getTransaction().commit();
                        requestFound = true;
                    }
                }

                if (!requestFound) {
                    logger.info("Request not found");
                    createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(),
                            messageBody);
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                }
            } catch (Exception e) {
                if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
                    hibernate.getTransaction().rollback();
                }

                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
            hibernate.getTransaction().rollback();
        }

        logger.error(e.getMessage(), e);
    }
}