Example usage for javax.mail Folder close

List of usage examples for javax.mail Folder close

Introduction

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

Prototype

public abstract void close(boolean expunge) throws MessagingException;

Source Link

Document

Close this Folder.

Usage

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*w  w w.j  a va  2 s  .c  o m*/
    result.setNrErrors(1);

    FileObject fileObject = null;

    //Get system properties

    //Properties prop = System.getProperties();
    Properties prop = new Properties();

    //Create session object
    //Session sess = Session.getDefaultInstance(prop,null);
    Session sess = Session.getInstance(prop, null);
    sess.setDebug(true);

    try {

        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        fileObject = KettleVFS.getFileObject(getRealOutputDirectory());

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory()
                            + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label"));
        } else {

            String host = getRealServername();
            String user = getRealUsername();
            String pwd = getRealPassword();

            Store st = null;

            if (!getUseSSL()) {

                //Create POP3 object               
                st = sess.getStore("pop3");

                // Try to connect to the server
                st.connect(host, user, pwd);
            } else {
                // Ssupports POP3 connection with SSL, the connection is established via SSL.

                String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

                //Properties pop3Props = new Properties();

                prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
                prop.setProperty("mail.pop3.socketFactory.fallback", "false");
                prop.setProperty("mail.pop3.port", getRealSSLPort());
                prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort());

                URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd);

                st = new POP3SSLStore(sess, url);

                st.connect();

            }

            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user);

            //Open default folder   INBOX 
            Folder f = st.getFolder("INBOX");
            f.open(Folder.READ_ONLY);

            if (f == null) {
                log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label"));

            } else {

                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label")
                                + f.getMessageCount());
                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label")
                                + f.getNewMessageCount());

                // Get emails 
                Message msg_list[] = getPOPMessages(f, retrievemails);

                if (msg_list.length > 0) {
                    List current_file_POP = new ArrayList();
                    List current_filepath_POP = new ArrayList();
                    int nb_email_POP = 1;
                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");

                    String startpattern = "name";
                    if (!Const.isEmpty(getRealFilenamePattern())) {
                        startpattern = getRealFilenamePattern();
                    }

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

                    {

                        /*if(msg[i].isMimeType("text/plain"))
                         {
                         log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]);
                         log.logDetailed(toString(), "Sujet: "+msg[i].getSubject());
                         log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent());
                                
                         }*/

                        if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) {

                            Message msg_POP = msg_list[i];
                            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label")
                                    + msg_list[i].getFrom()[0]);
                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.EmailSubject.Label")
                                            + msg_list[i].getSubject());

                            String localfilename_message = startpattern + "_" + dateFormat.format(new Date())
                                    + "_" + (i + 1) + ".mail";

                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label")
                                            + localfilename_message
                                            + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label"));

                            File filename_message = new File(getRealOutputDirectory(), localfilename_message);
                            OutputStream os_filename = new FileOutputStream(filename_message);
                            Enumeration enums_POP = msg_POP.getAllHeaders();
                            while (enums_POP.hasMoreElements())

                            {
                                Header header_POP = (Header) enums_POP.nextElement();
                                os_filename.write(new StringBuffer(header_POP.getName()).append(": ")
                                        .append(header_POP.getValue()).append("\r\n").toString().getBytes());
                            }
                            os_filename.write("\r\n".getBytes());
                            InputStream in_POP = msg_POP.getInputStream();
                            byte[] buffer_POP = new byte[1024];
                            int length_POP = 0;
                            while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                os_filename.write(buffer_POP, 0, length_POP);
                            }
                            os_filename.close();
                            nb_email_POP++;
                            current_file_POP.add(filename_message);
                            current_filepath_POP.add(filename_message.getPath());

                            if (delete) {
                                log.logDetailed(toString(),
                                        Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label"));
                                msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                            }
                        }

                    }
                }
                // Close and exit 
                if (f != null)
                    f.close(false);
                if (st != null)
                    st.close();

                f = null;
                st = null;
                sess = null;

                result.setNrErrors(0);
                result.setResult(true);

            }
        }

    }

    catch (NoSuchProviderException e) {
        log.logError(toString(), "provider error: " + e.getMessage());
    } catch (MessagingException e) {
        log.logError(toString(), "Message error: " + e.getMessage());
    }

    catch (Exception e) {
        log.logError(toString(), "Inexpected error: " + e.getMessage());
    }

    finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        sess = null;

    }

    return result;
}

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 av a 2 s .  c om

    // 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();

}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.//from ww  w  . j  av  a 2  s  . com
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // 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++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            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();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // 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 X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 *
 * @param request/*from  www . j a  v  a 2 s  .  c o m*/
 *        where request.action = [ "Send" , "Update" ,"Read" , "Save" ]
 * @return
 */
private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) {

    //System.out.println("===> sendImapSSLMail: Action= " + request.getAction());

    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;
    Folder folder = null; //the email server folder the msg is CURRENTLY in.

    String userType = "";
    String[] access = new String[2];

    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDTO foundContact = null;
    try {
        foundContact = findContactByUserId(userId);
    } catch (Exception e) {
        log.error("Contact record not found for userid: " + request.getUserId());
        response.setMessage("Contact record not found for userid: " + request.getUserId());
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid());

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    // Use the sslStore to send/change the message
    try {
        //action = Save
        if (request.getAction().equalsIgnoreCase("Save")) {
            response = saveDraft(request, access, sslStore,
                    this.mapKmrLocationToImapFolder("Drafts", this.host), session);
            response.setSuccessStatus(true);
            //return response;
        }
        //action = Send
        else if (request.getAction().equalsIgnoreCase("Send")) {
            // create and send msg to recipient(s).
            Message[] msgArr = createMessage(session, access[0], request);
            sendMessagesTOCCBCC(msgArr, request, session);

            // Store a copy to sender's Sent folder
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder("Sent", this.host));
            folder.appendMessages(msgArr);

            response.setSuccessStatus(true);
        }
        //action = ..any other..
        else {
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
            folder.open(Folder.READ_WRITE);

            //--------------------------------------------
            // Find the message by the given Message-ID
            //--------------------------------------------
            IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

            //--------------------------------------------
            // Process the message
            //--------------------------------------------
            if (imapMessage != null) {
                System.out.println("===> sendImapSSLMail:Updating:   action=" + request.getAction());
                System.out.println("===> sendImapSSLMail:Updating:   folder=" + folder.getName());
                System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID());

                updateImapSSLMail(request, folder, imapMessage);

                System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId="
                        + request.getMessageId());

                response.setSuccessStatus(true);

            } else {
                String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
                System.out.println("===> sendImapSSLMail: " + statMsg);

                response.setSuccessStatus(false);
                response.setMessage(statMsg);
            }

        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        return response;
    } finally {
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException me) {
                log.error("Error closing folder");
            }
        }
        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (MessagingException me) {
                log.error("Error closing SSLStore");
            }
        }
    }

    return response;

}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType archiveMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();

    IMAPSSLStore sslStore = null;//  w  w w  .j  a v a 2 s .  com
    Folder folder = null;
    Folder destinationFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    // INPUT:  request.getUserId()
    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    //PROCESSING the action.
    // folder --> the current folder the msg being processed is in.
    // destinationFolder --> the destination folder where the msg will be moved.
    try {

        //----------------------------------
        // Determine/Set destination folder
        //----------------------------------
        if (request.getAction().equals("Archive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "Archives");
        } else if (request.getAction().equals("Unarchive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        destinationFolder.open(Folder.READ_WRITE);

        //----------------------------------
        // Set originating folder
        //----------------------------------
        folder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
        folder.open(Folder.READ_WRITE);

        System.out.println(
                "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId()
                        + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName());

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

        //--------------------------------------------
        // Process the message
        //--------------------------------------------
        if (imapMessage != null) {
            Message[] messages = new Message[] { imapMessage };
            folder.copyMessages(messages, destinationFolder);
            imapMessage.setFlag(Flags.Flag.DELETED, true);
            folder.expunge();

            System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId="
                    + request.getMessageId());

            response.setSuccessStatus(true);

        } else {
            String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> " + statMsg);

            response.setSuccessStatus(false);
            response.setMessage(statMsg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage(
                "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;

    } finally {
        try {
            if ((folder != null) && folder.isOpen())
                folder.close(false);
            if ((destinationFolder != null) && destinationFolder.isOpen())
                destinationFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType deleteMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;/*from ww w.j  a va 2s  .c o m*/
    Folder sourceFolder = null;
    Folder targetFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN
    //        if (foundContact.getEmployeeNumber() != null) {
    //            userType = ITEM_ID_PROVIDER;
    //            access = retrieveMailAccess(userType, foundContact.getEmployeeNumber());
    //        }
    //        else {
    //            userType = ITEM_ID_PATIENT;
    //            access = retrieveMailAccess(userType, foundContact.getUid());
    //        }

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    try {

        //--------------------------
        // Set originating folder
        //--------------------------
        sourceFolder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));

        // Is this really needed if request comes in with location=UserTrash already?
        if (request.getAction().equals("Undelete")) {
            sourceFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        sourceFolder.open(Folder.READ_WRITE);

        //--------------------------
        // Set destination folder
        //--------------------------
        if (request.getAction().equals("Delete")) {
            targetFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        if (request.getAction().equals("DeleteForever")) {
            targetFolder = getImapFolder(session, sslStore, access, "AdminTrash");
        } else if (request.getAction().equals("Undelete")) {
            targetFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        targetFolder.open(Folder.READ_WRITE);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //-------------------------------------------
        Message msg = this.findMsgByMessageId(sourceFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> deleteMessage: " + errmsg);

            response.setSuccessStatus(false);
            response.setMessage(errmsg);

        } else {

            //this.printMsgIdSubject(msg); //DBG printout

            //----------------------
            //copy to new folder
            //----------------------
            Message[] messages = new Message[] { msg };
            sourceFolder.copyMessages(messages, targetFolder);

            //----------------------
            //remove from old folder
            //----------------------
            msg.setFlag(Flags.Flag.DELETED, true);
            sourceFolder.expunge();

            response.setSuccessStatus(true);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error archiving mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;
    } finally {
        try {
            sourceFolder.close(false);
            targetFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///from   w  ww .  j a v a  2s.c  o  m
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file: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 w  w . j av a  2  s.co  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:com.sonicle.webtop.mail.Service.java

public void hideFolder(MailAccount account, String foldername) throws MessagingException {
    Folder folder = account.getFolder(foldername);
    try {//  www .j  av  a  2s  .  c o  m
        folder.close(false);
    } catch (Throwable exc) {
    }
    account.destroyFolderCache(foldername);
    if (account == mainAccount)
        us.setFolderHidden(foldername, true);
    else
        us.setFolderHidden(mainAccount.getId() + "_" + foldername, true);
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

@SuppressWarnings({ "unchecked" })
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*  w w w.  j  a  va 2  s. c o  m*/
    result.setNrErrors(1);

    //Get system properties
    Properties prop = new Properties();
    prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    //Create session object
    Session sess = Session.getDefaultInstance(prop, null);
    sess.setDebug(true);

    FileObject fileObject = null;
    Store st = null;
    Folder f = null;
    try {
        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        String realOutputFolder = getRealOutputDirectory();
        fileObject = KettleVFS.getFileObject(realOutputFolder);

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$
        } else {
            if (fileObject.getType() == FileType.FOLDER) {
                String host = getRealServername();
                String user = getRealUsername();
                String pwd = getRealPassword();

                if (!getUseSSL()) {
                    //Create POP3 object
                    st = sess.getStore("pop3"); //$NON-NLS-1$

                    // Try to connect to the server
                    st.connect(host, user, pwd);
                } else {
                    // Ssupports POP3 connection with SSL, the connection is established via SSL.

                    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$
                    prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$

                    URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$
                    st = new POP3SSLStore(sess, url);
                    st.connect();
                }
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$

                //Open the INBOX FOLDER
                // For POP3, the only folder available is the INBOX.
                f = st.getFolder("INBOX"); //$NON-NLS-1$

                if (f == null) {
                    log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$

                } else {
                    // Open folder
                    if (delete)
                        f.open(Folder.READ_WRITE);
                    else
                        f.open(Folder.READ_ONLY);

                    Message messageList[] = f.getMessages();
                    if (log.isDetailed()) {
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$
                                        String.valueOf(messageList.length)));
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$
                                        f.getName(), String.valueOf(f.getUnreadMessageCount())));
                    }
                    // Get emails
                    Message msg_list[] = getPOPMessages(f, retrievemails);

                    if (msg_list.length > 0) {
                        List<File> current_file_POP = new ArrayList<File>();
                        List<String> current_filepath_POP = new ArrayList<String>();
                        int nb_email_POP = 1;

                        String startpattern = "name"; //$NON-NLS-1$
                        if (!Const.isEmpty(getRealFilenamePattern())) {
                            startpattern = getRealFilenamePattern();
                        }

                        for (int i = 0; i < msg_list.length; i++) {
                            if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2)
                                    || (retrievemails != 2)) {
                                Message msg_POP = msg_list[i];
                                if (log.isDetailed()) {
                                    log.logDetailed(toString(),
                                            Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$
                                                    msg_list[i].getFrom()[0].toString()));
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$
                                }
                                String localfilename_message = startpattern + "_" //$NON-NLS-1$
                                        + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$
                                if (log.isDetailed())
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$

                                File filename_message = new File(realOutputFolder, localfilename_message);
                                OutputStream os_filename = new FileOutputStream(filename_message);
                                Enumeration<Header> enums_POP = msg_POP.getAllHeaders();
                                while (enums_POP.hasMoreElements())

                                {
                                    Header header_POP = enums_POP.nextElement();
                                    os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$
                                            .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$
                                }
                                os_filename.write("\r\n".getBytes()); //$NON-NLS-1$
                                InputStream in_POP = msg_POP.getInputStream();
                                byte[] buffer_POP = new byte[1024];
                                int length_POP = 0;
                                while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                    os_filename.write(buffer_POP, 0, length_POP);

                                }
                                os_filename.close();
                                nb_email_POP++;
                                current_file_POP.add(filename_message);
                                current_filepath_POP.add(filename_message.getPath());

                                // Check attachments
                                Object content = msg_POP.getContent();
                                if (content instanceof Multipart) {
                                    handleMultipart(realOutputFolder, (Multipart) content);
                                }

                                // Check if mail has to be deleted
                                if (delete) {
                                    if (log.isDetailed())
                                        log.logDetailed(toString(),
                                                Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$
                                    msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                                }
                            }
                        }
                    }

                    result.setNrErrors(0);
                    result.setResult(true);
                }

            } else {
                log.logError(toString(),
                        Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder));
            }
        }
    } catch (NoSuchProviderException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$
    } catch (MessagingException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$
    } finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        //close the folder, passing in a true value to expunge the deleted message
        try {
            if (f != null)
                f.close(true);
            if (st != null)
                st.close();
        } catch (Exception e) {
            log.logError(toString(), e.getMessage());
        }
        // free memory
        f = null;
        st = null;
        sess = null;
    }

    return result;
}