Example usage for javax.mail Store connect

List of usage examples for javax.mail Store connect

Introduction

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

Prototype

public synchronized void connect(String host, int port, String user, String password)
        throws MessagingException 

Source Link

Document

Similar to connect(host, user, password) except a specific port can be specified.

Usage

From source file:org.apache.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {// w  w w .j  a  v a  2  s . c  o  m
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(pop3Host, pop3Port, mailAddress, mailPassword);

    Folder inbox = store.getFolder("INBOX");
    assertNotNull(inbox);
    inbox.open(Folder.READ_WRITE);

    Message[] messages = inbox.getMessages();
    for (int i = 0; i < messages.length; i++) {
        if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) {
            found = true;
            messages[i].setFlag(Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();
    return found;
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

protected Store connectToStore() throws MessagingException {
    EmailConfig config = getConfig();//from w w  w  .  j  av  a  2 s.c  o  m
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", provider.getIncomingProto());

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

    Store store = session.getStore(provider.getIncomingProto());
    store.connect(provider.getIncomingServer(), provider.getIncomingPort(), config.getUsername(),
            config.getPassword());
    return store;
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {//from   w  ww .jav  a  2 s.  c om
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(POP3_HOST, POP3_PORT, MAIL_ADDRESS, MAIL_PASSWORD);

    Folder inbox = store.getFolder("INBOX");
    assertNotNull(inbox);
    inbox.open(Folder.READ_WRITE);

    Message[] messages = inbox.getMessages();
    for (int i = 0; i < messages.length; i++) {
        if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) {
            found = true;
            messages[i].setFlag(Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();
    return found;
}

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

/**
 * {@inheritDoc}/*from  w w  w . j av  a2  s .  c o  m*/
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

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

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

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

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

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

public void testEightBitMessage() throws Exception {

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

    String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME;

    IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName);
    lfolder.open(Folder.READ_WRITE);/*  w  ww .  ja v  a2  s  .c  o  m*/

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

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

        Message[] messages = { message };

        lfolder.appendMessages(messages);

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

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

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

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

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

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

        NodeRef messageNodeRef = nodeRefs.get(0);

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

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

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

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

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

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

}

From source file:com.liferay.mail.imap.IMAPConnection.java

public Store getStore(boolean useOldStores) throws MailException {
    Store store = null;

    try {/*from www  . j  a va  2 s  . c o  m*/
        String storeKey = _incomingHostName.concat(_outgoingHostName).concat(_login);

        if (useOldStores) {
            store = _allStores.get(storeKey);

            if ((store != null) && !store.isConnected()) {
                store.close();

                store = null;
            }
        }

        if (store == null) {
            Session session = getSession();

            if (_incomingSecure) {
                store = session.getStore("imaps");
            } else {
                store = session.getStore("imap");
            }

            store.connect(_incomingHostName, _incomingPort, _login, _password);

            if (useOldStores) {
                _allStores.put(storeKey, store);
            }
        }

        return store;
    } catch (MessagingException me) {
        throw new MailException(MailException.ACCOUNT_INCOMING_CONNECTION_FAILED, me);
    }
}

From source file:com.zotoh.maedr.device.PopIO.java

private boolean conn() {

    if (_pop == null || !_pop.isConnected())
        try {//  ww w.j  a  v a 2 s .  c o m
            Session session = Session.getInstance(new Properties(), null);
            Provider[] ps = session.getProviders();
            Provider sun = null;
            Store st = null;
            Folder f = null;
            String uid = isEmpty(_user) ? null : _user;
            String pwd = isEmpty(_pwd) ? null : _pwd;
            String key = ST_POP3, sn = POP3;

            closePOP();

            if (_ssl) {
                key = ST_POP3S;
                sn = POP3S;
            }

            for (int i = 0; i < ps.length; ++i) {
                if (key.equals(ps[i].getClassName())) {
                    sun = ps[i];
                    break;
                }
            }

            if (!isEmpty(_storeImpl)) {
                // this should never happen , only in testing
                sun = new Provider(Provider.Type.STORE, "pop3", _storeImpl, "test", "1.0.0");
                sn = POP3;
            }

            session.setProvider(sun);
            st = session.getStore(sn);

            if (st != null) {
                st.connect(_host, _port, uid, pwd);
                f = st.getDefaultFolder();
            }

            if (f != null) {
                f = f.getFolder("INBOX");
            }

            if (f == null || !f.exists()) {
                throw new Exception("POP3: Cannot find inbox");
            }

            _pop = st;
            _fd = f;

        } catch (Exception e) {
            tlog().warn("", e);
            closePOP();
        }

    return _pop != null && _pop.isConnected();
}

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 
 **//*www . j  av a 2s .  c o  m*/

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

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

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

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

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

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

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

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

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

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