Java Code Examples for javax.mail.Store#connect()

The following examples show how to use javax.mail.Store#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Store connectStore() throws MessagingException {
	initProperties();
	if (isSSLRequired()) {
		return connectStoreSSL();
	}
	Properties properties = new Properties();
	properties.put("mail." + getProtocol() + ".timeout", TIMEOUT);
	properties.put("mail." + getProtocol() + ".connectiontimeout", TIMEOUT);
	//properties.setProperty("mail.store.protocol", getProtocol());
	Session session = Session.getInstance(properties, null);
	Store store = session.getStore(getProtocol());
	if (getIncomingPort() == 0) {
		store.connect(getIncomingHost(), getUsername(), getPassword());
	} else {
		store.connect(getIncomingHost(), getIncomingPort(), getUsername(), getPassword());
	}
	return store;
}
 
Example 2
Source File: ImapSubjectLineTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
private void testSubject(String subject) throws Exception {
    GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
    assertNotNull(greenMail.getImap());

    MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
    storeSearchTestMessages(greenMail.getImap().createSession(), folder, subject);

    greenMail.waitForIncomingEmail(1);

    final Store store = greenMail.getImap().createStore();
    store.connect("to1@localhost", "pwd");
    try {
        Folder imapFolder = store.getFolder("INBOX");
        imapFolder.open(Folder.READ_ONLY);

        Message[] imapMessages = imapFolder.getMessages();
        assertTrue(null != imapMessages && imapMessages.length == 1);
        Message imapMessage = imapMessages[0];
        assertEquals(subject.replaceAll("\\s+",""), imapMessage.getSubject().replaceAll("\\s+",""));
    } finally {
        store.close();
    }
}
 
Example 3
Source File: EmailUtils.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Connects to email server with credentials provided to read from a given folder of the email application
 *
 * @param username    Email username (e.g. [email protected])
 * @param password    Email password
 * @param server      Email server (e.g. smtp.email.com)
 * @param emailFolder Folder in email application to interact with
 */
public EmailUtils(String username, String password, String server, EmailFolder emailFolder)
        throws MessagingException {

    Properties props = System.getProperties();

    try {
        props.load(new FileInputStream(new File("../src/test/resources/email.properties")));
    } catch (Exception e) {
        logger.error("Error occured while reading email properties ", e);
        System.exit(-1);
    }

    Session session = Session.getInstance(props);
    Store store = session.getStore("imaps");
    store.connect(server, username, password);

    folder = store.getFolder(emailFolder.getText());
    folder.open(Folder.READ_WRITE);
}
 
Example 4
Source File: SMTPTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test3SendMessage() throws Exception {

    Session.getDefaultInstance(getProperties());

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    Transport.send(msg);

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
Example 5
Source File: imap.java    From jbang with MIT License 5 votes vote down vote up
@Override
public Integer call() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect(host, username, password);
    //System.out.println(store);

    Folder f = store.getFolder(folder);
    System.out.println(f.getName() + ":" + f.getUnreadMessageCount());

    return f.getUnreadMessageCount();
}
 
Example 6
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private Store openConnection( cfSession _Session ) throws cfmRunTimeException	{
	String server	 = getDynamic( _Session, "SERVER" ).getString();
	boolean secure = getSecure( _Session );
	int	port			 = getPort( _Session, secure );
	String user    = getDynamic( _Session, "USERNAME" ).getString();
	String pass    = getDynamic( _Session, "PASSWORD" ).getString();
	
	Properties props = new Properties();
	String protocol = "pop3";
	if ( secure ){
		protocol = "pop3s";
	}
	
	props.put( "mail.transport.protocol", protocol );
	props.put( "mail." + protocol + ".port", String.valueOf( port ) );
	
	// This is the fix for bug NA#3156
 	    props.put("mail.mime.address.strict", "false");
	
	// With WebLogic Server 8.1sp4 and an IMAIL server, we're seeing that sometimes the first
	// attempt to connect after messages have been deleted fails with either a MessagingException 
	// of "Connection reset" or an AuthenticationFailedException of "EOF on socket".  To work
	// around this let's try 3 attempts to connect before giving up.
	for ( int numAttempts = 1; numAttempts < 4; numAttempts++ )
	{
		try{
			Session session 	= Session.getInstance( props );
			Store mailStore		= session.getStore( protocol );
			mailStore.connect( server, user, pass );
			return mailStore;
		}catch(Exception E){
			if ( numAttempts == 3 )
				throw newRunTimeException( E.getMessage() );
		}
	}
	
	// The code in the for loop should either return or throw an exception
	// so this code should never get hit.
	return null;
}
 
Example 7
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendMessage() throws Exception {
    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getIMAPProvider("makes_no_difference_here", true, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    inbox.appendMessages(new MimeMessage[] { msg });

    Assert.assertEquals(4, inbox.getMessageCount());

    inbox.close(true);

}
 
Example 8
Source File: MalinatorUtil.java    From qaf with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		Properties props = new Properties();

		String host = "pop.mailinator.com";
		String username = "x-test-m";
		String password = "mypwdxxx";
		String provider = "pop3";

		Session session = Session.getDefaultInstance(props, null);
		Store store = session.getStore(provider);
		store.connect(host, username, password);

		Folder inbox = store.getFolder("INBOX");
		if (inbox == null) {
			System.out.println("No INBOX");
			System.exit(1);
		}
		inbox.open(Folder.READ_ONLY);

		Message[] messages = inbox.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Message " + (i + 1));
			messages[i].writeTo(System.out);
		}
		inbox.close(false);
		store.close();

	}
 
Example 9
Source File: LiveChatBean.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public Store connectStore() throws MessagingException {
	Properties properties = new Properties();
	properties.put("mail." + this.instance.getEmailProtocol() + ".timeout", 5000);
	properties.put("mail." + this.instance.getEmailProtocol() + ".connectiontimeout", 5000);
	//properties.setProperty("mail.store.protocol", getProtocol());
    Session session = Session.getInstance(properties, null);
    Store store = session.getStore(this.instance.getEmailProtocol());
    if (this.instance.getEmailIncomingPort() == 0) {
    	store.connect(this.instance.getEmailIncomingHost(), this.instance.getEmailUserName(), this.instance.getEmailPassword());
    } else {
    	store.connect(this.instance.getEmailIncomingHost(), this.instance.getEmailIncomingPort(), this.instance.getEmailUserName(), this.instance.getEmailPassword());
    }
    return store;
}
 
Example 10
Source File: PopMailImporter.java    From mireka with Apache License 2.0 5 votes vote down vote up
private void importMails(GlobalUser user) throws MessagingException {
    logger.debug("Importing mail for " + user.getUsernameObject());
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://"
                    + user.getUsernameObject() + ":" + user.getPassword()
                    + "@" + remoteHost + ":" + +remotePort + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    int cSuccessfulMails = 0;
    // user name currently equals with the maildrop name, but this is
    // not necessarily true in general.
    String maildropName = user.getUsernameObject().toString();
    for (Message message : messages) {
        try {
            importMail(maildropName, message);
            message.setFlag(Flags.Flag.DELETED, true);
            cSuccessfulMails++;
        } catch (Exception e) {
            logger.error("Importing a mail for " + user.getUsernameObject()
                    + " failed", e);
        }
    }
    folder.close(true);
    store.close();
    totalMailCount += cSuccessfulMails;
    if (cSuccessfulMails > 0)
        totalUsersWithAtLeastOneMail++;
    logger.debug(cSuccessfulMails + " mails were imported for "
            + user.getUsernameObject());
}
 
Example 11
Source File: MockImapClient.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public Store connect( Session session ) throws MessagingException {
    logger.info( "getting the session for accessing email." );
    Store store = session.getStore( "imap" );

    store.connect( host, user, password );
    logger.info( "Connection established with IMAP server." );
    return store;
}
 
Example 12
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 5 votes vote down vote up
protected void renameMailbox(final Properties props, final String folderName, final String user, final String password)
        throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);

    f.renameTo(store.getFolder("renamed_from_" + folderName));

    logger.info("Renamed " + f.getFullName());
    store.close();

}
 
Example 13
Source File: ReceiveEMailVerifierExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {
        MailConfiguration configuration = createConfiguration(parameters);

        String timeoutVal = ConnectorOptions.extractOption(parameters, CONNECTION_TIMEOUT);
        if (ObjectHelper.isEmpty(timeoutVal)) {
            timeoutVal = Long.toString(DEFAULT_CONNECTION_TIMEOUT);
        }

        setConnectionTimeoutProperty(parameters, configuration, timeoutVal);

        JavaMailSender sender = createJavaMailSender(configuration);
        Session session = sender.getSession();

        Store store = session.getStore(configuration.getProtocol());
        try {
            store.connect(configuration.getHost(), configuration.getPort(),
                          configuration.getUsername(), configuration.getPassword());
        } finally {
            if (store.isConnected()) {
                store.close();
            }
        }
    } catch (Exception e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
            .detail("mail_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
            .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    }

    return builder.build();
}
 
Example 14
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testOnlyInbox() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getPOP3Provider("makes_no_differernce", false, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();

    try {
        defaultFolder.getFolder("test");
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example 15
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13

    final Store store = session.getStore();
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_WRITE);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);

    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example 16
Source File: MiscTest.java    From jqm with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmail() throws Exception
{
    // Do not run in Eclipse, as it does not support the SMTP Maven plugin.
    Assume.assumeTrue(!System.getProperty("java.class.path").contains("eclipse"));

    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar", TestHelpers.qVip, 42,
            "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true, cnx);
    JobRequest.create("MarsuApplication", "TestUser").setEmail("[email protected]").submit();

    addAndStartEngine();
    TestHelpers.waitFor(1, 20000, cnx); // Need time for async mail sending.

    Assert.assertEquals(1, TestHelpers.getOkCount(cnx));
    Assert.assertEquals(0, TestHelpers.getNonOkCount(cnx));

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imap");
    int nbMail = 0;
    try
    {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("localhost", 10143, "testlogin", "testpassword");
        Folder inbox = store.getFolder("INBOX");
        nbMail = inbox.getMessageCount();
    }
    catch (Exception mex)
    {
        mex.printStackTrace();
    }
    Assert.assertEquals(1, nbMail);
}
 
Example 17
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e){
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}
 
Example 18
Source File: ParallelPollingPOPMailSource.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
private ProcessResult processMessageSlice(final int start, final int end, final String folderName) throws Exception {

        final long startTime = System.currentTimeMillis();
        final Store store = Session.getInstance(props).getStore();
        store.connect(user, password);
        final Folder folder = store.getFolder(folderName);

        IMAPUtils.open(folder);

        try {

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

            int processedCount = 0;

            for (final Message m : msgs) {
                try {
                    mailDestination.onMessage(m);
                    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;
            return new ProcessResult(processedCount, endTime - startTime);

        } finally {

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

    }
 
Example 19
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}
 
Example 20
Source File: ParallelPollingIMAPMailSource.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
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);
        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);
        }

    }