Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

In this page you can find the example usage for javax.mail Session getInstance.

Prototype

public static Session getInstance(Properties props) 

Source Link

Document

Get a new Session object.

Usage

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

private ProcessResult processMessageSlice(final int start, final int end, final String folderName)
        throws Exception {

    logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName);
    final long startTime = System.currentTimeMillis();
    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);// www  .j ava  2  s.c  o m
    final Folder folder = store.getFolder(folderName);
    final UIDFolder uidfolder = (UIDFolder) folder;

    IMAPUtils.open(folder);

    try {

        final Message[] msgs = folder.getMessages(start, end);
        folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD);

        logger.debug("folder fetch done");

        long highestUid = 0;
        int processedCount = 0;

        for (final Message m : msgs) {
            try {

                IMAPUtils.open(folder);
                final long uid = uidfolder.getUID(m);

                mailDestination.onMessage(m);

                highestUid = Math.max(highestUid, uid);
                processedCount++;

                if (Thread.currentThread().isInterrupted()) {
                    break;
                }

            } catch (final Exception e) {
                stateManager.onError("Unable to make indexable message", m, e);
                logger.error("Unable to make indexable message due to {}", e, e.toString());

                IMAPUtils.open(folder);
            }
        }

        final long endTime = System.currentTimeMillis() + 1;
        final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime);
        logger.debug("processMessageSlice() ended with " + pr);
        return pr;

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);
    }

}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here",
            Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);//  w w  w.  j  av  a2s .c om

    // We also test using some default BCC addresses from configuration in this test
    this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));

    // Ensure we do not reuse the same message identifier for multiple similar messages in this test
    MimeMessage message2 = new MimeMessage(message);
    message2.saveChanges();
    MimeMessage message3 = new MimeMessage(message);
    message3.saveChanges();

    // Step 4: Send the mail and wait for it to be sent
    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);

    // Note: we don't test status reporting from the listener since this is already tested in the
    // ScriptingIntegrationTest test class.

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 3);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
    assertEquals(9, messages.length);

    // Assert the email parts that are the same for all mails
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
    // messages ;) But we checked that we received 9 emails above so that's good enough.
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/* w  w w  .  j a v  a2  s  .com*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);//from  www . ja v a2 s.c  o  m
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}

From source file:com.abid_mujtaba.fetchheaders.models.Account.java

public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain.
{
    Properties props = new Properties();

    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imaps.host", mHost);
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication
    props.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(props);

    try {/*from   w w w .  ja v a2  s  .  c om*/
        Store store = imapSession.getStore("imaps");

        // Connect to server by sending username and password:
        store.connect(mHost, mUsername, mPassword);

        mInbox = store.getFolder("Inbox");
        mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later

        mTrash = store.getFolder("Trash");

        if (!mTrash.exists()) {
            mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named
            mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail

            if (!mTrash.exists()) {
                mTrash = null; // No trash folder found. Emails will be deleted directly
                mUsesLabels = false;
            }
        }

        int num = mInbox.getMessageCount(); // Get number of messages in the Inbox

        if (num > mMaxNumOfEmails) {
            mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on.
        } else {
            mMessages = mInbox.getMessages();
        }

        FetchProfile fp = new FetchProfile();
        fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data
        fp.add(FetchProfile.Item.FLAGS); // Fetch flags

        mInbox.fetch(mMessages, fp);

        // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order

        Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent

        mEmails = new SparseArray<Email>();

        for (int ii = 0; ii < mMessages.length; ii++) {
            Email email = new Email(mMessages[ii]);

            mEmails.put(ii, email);
        }

        return mEmails;
    } catch (MessagingException e) {
        Resources.Loge("Exception while attempting to connect to mail server", e);
        throw e;
    } // The two above exceptions are caught by this one if they are not explicitly stated above.
}

From source file:org.xwiki.mail.internal.FileSystemMailContentStoreTest.java

@Test
public void loadMessage() throws Exception {
    String batchId = UUID.randomUUID().toString();
    String messageId = "ar1vm0Wca42E/dDn3dsH8ogs3/s=";
    String mimeMessageId = "<1128820400.0.1419205781342.JavaMail.contact@xwiki.org>";

    File tempDir = new File(TEMPORARY_DIRECTORY);
    File batchDirectory = new File(new File(tempDir, this.mocker.getComponentUnderTest().ROOT_DIRECTORY),
            URLEncoder.encode(batchId, "UTF-8"));
    batchDirectory.mkdirs();/* ww  w .  j a va  2s  .c om*/
    File messageFile = new File(batchDirectory, URLEncoder.encode(messageId, "UTF-8"));
    messageFile.createNewFile();

    String newLine = System.getProperty("line.separator");

    FileWriter fileWriter = new FileWriter(messageFile, true);
    // Unique string is <hashcode>.<id>.<currentTime>.JavaMail.<suffix>
    fileWriter.append("Message-ID: " + mimeMessageId + newLine);
    fileWriter.append("MIME-Version: 1.0" + newLine);
    fileWriter.append("Content-Type: text/plain; charset=us-ascii" + newLine);
    fileWriter.append("Content-Transfer-Encoding: 7bit" + newLine + newLine);
    fileWriter.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit");
    fileWriter.close();

    Session session = Session.getInstance(new Properties());
    MimeMessage message = this.mocker.getComponentUnderTest().load(session, batchId, messageId);

    assertEquals(mimeMessageId, message.getMessageID());
    assertEquals("Lorem ipsum dolor sit amet, consectetur adipiscing elit", message.getContent());
}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Returns the default mail session that can be used to create a new message.
 * /*from  w w  w.j  a va  2s  . com*/
 * @return the default mail session
 */
public Session getSession() {
    if (defaultMailSession == null) {
        defaultMailSession = Session.getInstance(mailProperties);
    }
    return defaultMailSession;
}

From source file:ste.xtest.mail.BugFreeFileTransport.java

@Test
public void configuration_from_local_or_system() throws Exception {
    config.remove(MAIL_FILE_PATH);/*  www  .  j a  v  a 2  s  . co  m*/
    config.remove(MAIL_FILE_REQUIRE_SSL);

    //
    // system property $MAIL_FILE_PATH set in setUp()
    //
    System.setProperty(MAIL_FILE_PATH, "path_from_system");

    Session s = Session.getInstance(config);
    FileTransport t = (FileTransport) s.getTransport();
    then(t.getProperty(MAIL_FILE_PATH)).isEqualTo("path_from_system");

    //
    // local property overrides system property
    //
    config.setProperty(MAIL_FILE_PATH, "path_from_local");
    s = Session.getInstance(config);
    t = (FileTransport) s.getTransport();
    then(t.getProperty(MAIL_FILE_PATH)).isEqualTo("path_from_local");

    //
    // system property $MAIL_FILE_REQUIRE_TLS set in setUp()
    //
    System.setProperty(MAIL_FILE_REQUIRE_SSL, "tls_from_system");

    s = Session.getInstance(config);
    t = (FileTransport) s.getTransport();
    then(t.getProperty(MAIL_FILE_REQUIRE_SSL)).isEqualTo("tls_from_system");

    //
    // local property overrides system property
    //
    config.setProperty(MAIL_FILE_REQUIRE_SSL, "tls_from_local");
    s = Session.getInstance(config);
    t = (FileTransport) s.getTransport();
    then(t.getProperty(MAIL_FILE_REQUIRE_SSL)).isEqualTo("tls_from_local");
}

From source file:org.xwiki.mail.internal.FileSystemMailContentStoreTest.java

@Test
public void loadMessageThrowsMailStoreExceptionWhenError() throws Exception {
    String batchId = UUID.randomUUID().toString();
    String messageId = "ar1vm0Wca42E/dDn3dsH8ogs3/s=";
    Session session = Session.getInstance(new Properties());

    this.thrown.expect(MailStoreException.class);
    this.thrown.expectMessage(
            "Failed to load message (id [" + messageId + "], batch id [" + batchId + "]) from file");

    MimeMessage message = this.mocker.getComponentUnderTest().load(session, batchId, messageId);
    fail("Should have thrown an exception here");
}

From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java

protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
        throws MessagingException {
    String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
    String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
    if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
        mailService = getMailService();//www  . j ava 2  s  . c  o  m

        MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);

        Visitor visitor = new Visitor(pipe);
        Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();

        initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());

        initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());

        initialExecutionContext.put(CORE_SESSION_KEY, coreSession);

        initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
                                                                        // schema

        Folder rootFolder = null;
        Store store = null;
        try {
            String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
            initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
            // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));

            String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
            String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
            Boolean socketFactoryFallback = (Boolean) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
            String socketFactoryPort = (String) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
            Boolean starttlsEnable = (Boolean) currentMailFolder
                    .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
            String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
            Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
            long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();

            String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");

            Properties properties = new Properties();
            properties.put("mail.store.protocol", protocolType);
            // properties.put("mail.host", host);
            // Is IMAP connection
            if (IMAP.equals(protocolType)) {
                properties.put("mail.imap.host", host);
                properties.put("mail.imap.port", port);
                properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imap.debug", imapDebug);
                properties.put("mail.imap.partialfetch", "false");
            } else if (IMAPS.equals(protocolType)) {
                properties.put("mail.imaps.host", host);
                properties.put("mail.imaps.port", port);
                properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imaps.ssl.protocols", sslProtocols);
                properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
                properties.put("mail.imap.partialfetch", "false");
                properties.put("mail.imaps.partialfetch", "false");
            } else if (POP3S.equals(protocolType)) {
                properties.put("mail.pop3s.host", host);
                properties.put("mail.pop3s.port", port);
                properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
                properties.put("mail.pop3s.ssl.protocols", sslProtocols);
            } else {
                // Is POP3 connection
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", port);
            }

            properties.put("user", email);
            properties.put("password", password);

            Session session = Session.getInstance(properties);

            store = session.getStore();
            store.connect(email, password);

            String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
            rootFolder = store.getFolder(folderName);

            // need RW access to update message flags
            rootFolder.open(Folder.READ_WRITE);

            Message[] allMessages = rootFolder.getMessages();
            // VDU
            log.debug("nbr of messages in folder:" + allMessages.length);

            FetchProfile fetchProfile = new FetchProfile();
            fetchProfile.add(FetchProfile.Item.FLAGS);
            fetchProfile.add(FetchProfile.Item.ENVELOPE);
            fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
            fetchProfile.add("Message-ID");
            fetchProfile.add("Content-Transfer-Encoding");

            rootFolder.fetch(allMessages, fetchProfile);

            if (rootFolder instanceof IMAPFolder) {
                // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
            }

            List<Message> unreadMessagesList = new ArrayList<Message>();
            for (Message message : allMessages) {
                Flags flags = message.getFlags();
                int unreadMessagesListSize = unreadMessagesList.size();
                if (flags != null && !flags.contains(Flag.SEEN)
                        && unreadMessagesListSize < emailsLimitLongValue) {
                    unreadMessagesList.add(message);
                    if (unreadMessagesListSize == emailsLimitLongValue - 1) {
                        break;
                    }
                }
            }

            Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);

            // perform email import
            visitor.visit(unreadMessagesArray, initialExecutionContext);

            // perform flag update globally
            Flags flags = new Flags();
            flags.add(Flag.SEEN);

            boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
            if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
                flags.add(Flag.SEEN);
            } else {
                flags.add(Flag.DELETED);
            }
            rootFolder.setFlags(unreadMessagesArray, flags, true);

        } finally {
            if (rootFolder != null && rootFolder.isOpen()) {
                rootFolder.close(true);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}