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

The following examples show how to use javax.mail.Store#close() . 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: GreenMailServer.java    From micro-integrator with Apache License 2.0 9 votes vote down vote up
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
                                               GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
Example 2
Source File: GreenMailServer.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example 3
Source File: EmailUtil.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    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 sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
Example 4
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Close connection
 * <b>Note</b>Internal method
 * @throws MessagingException
 */
public void closeStoreConnection(
                                  boolean storeConnected ) throws MessagingException {

    if (storeConnected) {
        // the folder is empty when the message is not loaded from IMAP server, but from a file
        Folder imapFolder = message.getFolder();
        if (imapFolder == null) {
            imapFolder = partOfImapFolder; // in case of nested package but still originating from IMAP server
        }
        if (imapFolder != null) {
            Store store = imapFolder.getStore();
            if (store != null && store.isConnected()) {
                // closing store closes and its folders
                log.debug("Closing store (" + store.toString() + ") and associated folders");
                store.close();
            }
        }
    }
}
 
Example 5
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 6
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 6 votes vote down vote up
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount,
        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.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}
 
Example 7
Source File: MessageParser.java    From OA with GNU General Public License v3.0 6 votes vote down vote up
public static void parse(Message... messages) {
	if (messages == null || messages.length == 0) {
		System.out.println("没有任何邮件");
	} else {
		for (Message m : messages) {
			parse(m);
		}
		// 最后关闭连接
		if (messages[0] != null) {
			Folder folder = messages[0].getFolder();
			if (folder != null) {
				try {
					Store store = folder.getStore();
					folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
					if (store != null) {
						store.close();
					}
				} catch (MessagingException e) {
					// ignore
				}
			}
		}
	}

}
 
Example 8
Source File: DockerServiceIT.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllServices() throws MessagingException, InterruptedException {
    // Ugly workaround : GreenMail in docker starts with open TCP connections,
    //                   but TLS sockets might not be ready yet.
    TimeUnit.SECONDS.sleep(1);

    // Send messages via SMTP and secure SMTPS
    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost",
            "test1", "Test GreenMail Docker service",
            ServerSetupTest.SMTP.createCopy(bindAddress));
    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost",
            "test2", "Test GreenMail Docker service",
            ServerSetupTest.SMTPS.createCopy(bindAddress));

    // IMAP
    for (ServerSetup setup : Arrays.asList(
            ServerSetupTest.IMAP.createCopy(bindAddress),
            ServerSetupTest.IMAPS.createCopy(bindAddress),
            ServerSetupTest.POP3.createCopy(bindAddress),
            ServerSetupTest.POP3S.createCopy(bindAddress))) {
        final Store store = Session.getInstance(setup.configureJavaMailSessionProperties(null, false)).getStore();
        store.connect("foo@localhost", "foo@localhost");
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            assertEquals("Can not check mails using "+store.getURLName(), 2, folder.getMessageCount());
        } finally {
            store.close();
        }
    }
}
 
Example 9
Source File: PortalTester.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the latest email with the given subject from the email inbox.
 * 
 * @param subject
 *            the email subject
 * @return the email body or null if no email was found
 * @throws Exception
 */
public String readLatestEmailWithSubject(String subject) throws Exception {
    Store store = mailSession.getStore();
    store.connect();

    Folder folder = store.getFolder(MAIL_INBOX);
    folder.open(Folder.READ_WRITE);

    Message[] messages = null;

    messages = folder.search(new SubjectTerm(subject));

    String body = null;
    if (messages.length > 0) {
        Message latest = messages[0];

        for (Message m : messages) {
            if (latest.getSentDate().compareTo(m.getSentDate()) < 0) {
                latest = m;
            }
        }
        body = (String) latest.getContent();
    }

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

    return body;
}
 
Example 10
Source File: MailToTransportUtil.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example 11
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 12
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * �����ʼ�
 */ 
public static void receive() throws Exception { 
    // ׼�����ӷ������ĻỰ��Ϣ 
    Properties props = new Properties(); 
    props.setProperty("mail.store.protocol", "pop3");       // �� 
    props.setProperty("mail.pop3.port", "110");             // �˿� 
    props.setProperty("mail.pop3.host", "pop3.sina.com");    // pop3������ 
     
    // ����Sessionʵ������ 
    Session session = Session.getInstance(props); 
    Store store = session.getStore("pop3"); 
    store.connect("[email protected]", "mh899821671104"); 
     
    // ����ռ��� 
    Folder folder = store.getFolder("INBOX"); 
    /* Folder.READ_ONLY��ֻ��Ȩ��
     * Folder.READ_WRITE���ɶ���д�������޸��ʼ���״̬��
     */ 
    folder.open(Folder.READ_WRITE); //���ռ��� 
     
    // ����POP3Э���޷���֪�ʼ���״̬,����getUnreadMessageCount�õ������ռ�����ʼ����� 
    System.out.println("δ���ʼ���: " + folder.getUnreadMessageCount()); 
     
    // ����POP3Э���޷���֪�ʼ���״̬,��������õ��Ľ��ʼ�ն���Ϊ0 
    System.out.println("ɾ���ʼ���: " + folder.getDeletedMessageCount()); 
    System.out.println("���ʼ�: " + folder.getNewMessageCount()); 
     
    // ����ռ����е��ʼ����� 
    System.out.println("�ʼ�����: " + folder.getMessageCount()); 
     
    // �õ��ռ����е������ʼ�,������ 
    Message[] messages = folder.getMessages(); 
    parseMessage(messages); 
     
    //�ͷ���Դ 
    folder.close(true); 
    store.close(); 
}
 
Example 13
Source File: AbstractNotificationTaskITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static boolean pop3(final String sender, final String subject, final String mailAddress) throws Exception {
    boolean found = false;
    Store store = null;
    try {
        store = Session.getDefaultInstance(System.getProperties()).getStore("pop3");
        store.connect(POP3_HOST, POP3_PORT, mailAddress, mailAddress);

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

        Message[] messages = inbox.getMessages();
        for (Message message : messages) {
            if (sender.equals(message.getFrom()[0].toString()) && subject.equals(message.getSubject())) {
                found = true;
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }

        inbox.close(true);
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return found;
}
 
Example 14
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 15
Source File: MailToTransportUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the email emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
Example 16
Source File: DefaultReceiveEmailProvider.java    From xframium-java with GNU General Public License v3.0 4 votes vote down vote up
public MessageWrapper _getEmail( String hostName, MessageFilter[] messageFilters, Map<String, String> propertyMap )
{
    Properties mailProps = new Properties();
    mailProps.putAll( propertyMap );

    List<Message> messageList = new ArrayList<Message>( 10 );
    MessageWrapper messageWrapper = null;

    try
    {
        Session emailSession = Session.getDefaultInstance( mailProps );
        Store store = emailSession.getStore( propertyMap.get( PROTOCOL ) );
        store.connect( hostName, propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) );

        Folder emailFolder = store.getFolder( propertyMap.get( FOLDER_NAME ) != null ? propertyMap.get( FOLDER_NAME ) : DEFAULT_FOLDER_NAME );
        emailFolder.open( Folder.READ_WRITE );

        Message[] messages = emailFolder.getMessages();

        int messageCount = emailFolder.getMessageCount();
        if ( messageCount > MAX_MESSAGES )
            messageCount = MAX_MESSAGES;

        if ( log.isInfoEnabled() )
            log.info( "Processing " + messageCount + " messages" );

        for ( int i = 0; i < messageCount; i++ )
        {
            if ( applyFilters( messages[i], messageFilters ) )
            {
                messageList.add( messages[i] );
            }
        }

        if ( messageList.size() == 0 )
            throw new ScriptException( "Failed to find any email messages that met the criteria" );
            
        Collections.sort( messageList, new DateComparator() );

        String messageContent = null;
        String contentType = messageList.get( 0 ).getContentType();

        if ( contentType.startsWith( "text/" ) )
            messageContent = messageList.get( 0 ).getContent().toString();
        else if ( messageList.get( 0 ).isMimeType( "multipart/*" ) )
            messageContent = getTextFromMimeMultipart( (MimeMultipart) messageList.get( 0 ).getContent() );
        else
            messageContent = messageList.get( 0 ).getContent().getClass().getName();

        messageWrapper = new MessageWrapper( messageList.size(), messageList.get( 0 ).getFrom()[0].toString(), messageList.get( 0 ).getSubject(), messageContent, contentType );

        emailFolder.close( false );
        store.close();
    }
    catch ( Exception e )
    {
        e.printStackTrace();
        throw new ScriptException( "Failed to find email" );
    }

    return messageWrapper;
}
 
Example 17
Source File: POP3Client.java    From OA with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
        Properties props = System.getProperties();
        String host = "pop3.163.com";
        String username = "[email protected]";
        String password = "song5438";
        String provider = "pop3";
        try {
            // 连接到POP3服务器
            Session ss = Session.getDefaultInstance(props, null);
            ss.setDebug(false);
            // 向回话"请求"一个某种提供者的存储库,是一个POP3提供者
            Store store = ss.getStore(provider);
            // 连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的
            store.connect(host, username, password);
            // 打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息
            // 从存储库的默认文件夹INBOX中读取邮件
            Folder inbox = store.getFolder("INBOX");
            if (inbox == null) {
                System.out.println("NO INBOX");
                System.exit(1);
            }
            // 打开文件夹,读取信息
            inbox.open(Folder.READ_ONLY);
            System.out.println("TOTAL EMAIL:" + inbox.getMessageCount());
            // 获取邮件服务器中的邮件
            Message[] messages = inbox.getMessages();
            for (int i = 0; i < messages.length; i++) {
                System.out.println("------------Message--" + (i + 1)
                        + "------------");
                // 解析地址为字符串
                String from = InternetAddress.toString(messages[i].getFrom());
                if (from != null) {
                    String cin = getChineseFrom(from);
                    System.out.println("From:" + cin);
                }
                String replyTo = InternetAddress.toString(messages[i]
                        .getReplyTo());
                if (replyTo != null){
                    String rest = getChineseFrom(replyTo);
                    System.out.println("Reply To" + rest);
                }
                String to = InternetAddress.toString(messages[i]
                        .getRecipients(Message.RecipientType.TO));
                if (to != null) {
                    String tos = getChineseFrom(to);
                    System.out.println("To:" + tos);
                }
                String subject = messages[i].getSubject();
                if (subject != null)
                    System.out.println("Subject:" + subject);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sent = messages[i].getSentDate();
                if (sent != null)
                    System.out.println("Sent Date:" + sdf.format(sent));
                Date ress = messages[i].getReceivedDate();
                if (ress != null)
                    System.out.println("Receive Date:" + sdf.format(ress));
         
//                Multipart multipart = (Multipart)messages[i].getContent();
//                for (int j=0, n=multipart.getCount(); j<n; j++) {
//                Part part = multipart.getBodyPart(j); 
//                String disposition = part.getDisposition(); 
//                if ((disposition != null) && (disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE))) {   
////                	saveFile(part.getFileName(), part.getInputStream());
//                 }
//                }
            }
            // 关闭连接,但不删除服务器上的消息
            // false代表不是删除
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
 
Example 18
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 19
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 20
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private static void closeConnection( Store store ) {
	try{
		if ( store != null ) store.close();
	}catch(Exception ignoreE){}
}