Java Code Examples for javax.mail.Folder#open()

The following examples show how to use javax.mail.Folder#open() . 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 product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user whose mail store should be connected
 * @param subject the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
Example 2
Source File: GreenMailServer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user     whose mail store should be connected
 * @param subject  the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
Example 3
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 4
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 5
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
// (expected = MockTestException.class)
public void testAppendFailMessage() 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();
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_ONLY);

    try {
        inbox.appendMessages(new MimeMessage[] { msg });
    } catch (final IllegalStateException e) {
        // throw new MockTestException(e);
    }

    // Assert.fail("Exception expected before this point");

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

    inbox.close(false);

}
 
Example 6
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 7
Source File: ArdulinkMailOnCamelIntegrationTest.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private Message retrieveViaImap(String host, int port, String user, String password) throws MessagingException {
	Properties props = new Properties();
	props.setProperty("mail.store.protocol", "imap");
	props.setProperty("mail.imap.port", String.valueOf(port));
	Session session = Session.getInstance(props, null);
	Store store = session.getStore();
	store.connect(host, user, password);
	Folder inbox = store.getFolder("INBOX");
	inbox.open(Folder.READ_ONLY);
	int messageCount = inbox.getMessageCount();
	return messageCount == 0 ? null : inbox.getMessage(1);
}
 
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: 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 10
Source File: POP3TestCase.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_ONLY);
    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

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

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

    inbox.close(true);
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof POP3Folder);
    Assert.assertEquals("12", ((POP3Folder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example 11
Source File: StoreDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private void deleteTargetMessages(Folder targetFolder) throws MessagingException {
    if (targetFolder != null) {
        final String targetFolderName = targetFolder.getFullName();
        final String sourceFolderName = targetToSourceFolderName(targetFolderName, sourceIndex, targetIndex);
        if ((targetFolder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
            targetFolder.open(Folder.READ_WRITE);
            if (targetFolder.getMode() != Folder.READ_ONLY) {
                targetFolder.expunge();
            }
            final int messageCount = targetFolder.getMessageCount();
            targetFolder.close(false);
            int pos = 1;
            while (pos + MNIMAPSync.BATCH_SIZE <= messageCount) {
                service.execute(
                        new MessageDeleter(this, targetFolderName, pos,
                                pos + MNIMAPSync.BATCH_SIZE, false, sourceIndex.
                                getFolderMessages(sourceFolderName)));
                pos = pos + MNIMAPSync.BATCH_SIZE;
            }
            service.execute(new MessageDeleter(this, targetFolderName,
                    pos, messageCount, true, sourceIndex.getFolderMessages(sourceFolderName)));
        }
        //Folder recursion. Get all children
        if ((targetFolder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
            for (Folder child : targetFolder.list()) {
                deleteTargetMessages(child);
            }
        }
    }
}
 
Example 12
Source File: AbstractMailExampleTest.java    From wildfly-camel-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void sendEmailTest() throws Exception {
    try {
        deployer.deploy(GREENMAIL_WAR);
        deployer.deploy(getDeploymentName());

        StringBuilder endpointURL = new StringBuilder("from=user1@localhost");
        endpointURL.append("&to=user2@localhost")
                .append("&subject=Greetings")
                .append("&message=Hello");

        HttpRequest.HttpResponse result = HttpRequest.post(getEndpointAddress("send"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .content(endpointURL.toString())
                .getResponse();

        String responseBody = result.getBody();
        Assert.assertTrue("Sent successful: " + responseBody, responseBody.contains("Message sent successfully"));

        // Verify that the email made it to the target address
        Store store = mailSession.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Assert.assertEquals(1, folder.getMessageCount());
    } finally {
        deployer.undeploy(getDeploymentName());
        deployer.undeploy(GREENMAIL_WAR);
    }
}
 
Example 13
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 14
Source File: MessageDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public void run() {
    long deleted = 0L;
    long skipped = 0L;
    try {
        final Folder targetFolder = storeDeleter.getTargetStore().getFolder(targetFolderName);
        //Opens a new connection per Thread
        targetFolder.open(Folder.READ_WRITE);
        final Message[] targetMessages = targetFolder.getMessages(start, end);
        targetFolder.fetch(targetMessages, MessageId.addHeaders(new FetchProfile()));
        for (Message message : targetMessages) {
            try {
                final MessageId id = new MessageId(message);
                if (!sourceFolderMessages.contains(id)) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    deleted++;
                } else {
                    skipped++;
                }
            } catch (MessageId.MessageIdException ex) {
                //Usually messages that ran into this exception are spammy, so we skip them.
                skipped++;
            }
        }
        //Close folder and expunge flagged messages
        //Expunge only if folder is read write
        if (targetFolder.getMode() == Folder.READ_ONLY) {
            targetFolder.close(false);
        } else {
            targetFolder.close(expunge);
        }
    } catch (MessagingException messagingException) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, messagingException);
    }
    storeDeleter.updatedMessagesDeletedCount(deleted);
    storeDeleter.updateMessagesSkippedCount(skipped);
}
 
Example 15
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private Folder openFolder( cfSession _Session, Store popStore )  throws cfmRunTimeException	{
	try{
		Folder folder = popStore.getDefaultFolder();
		Folder popFolder = folder.getFolder("INBOX");
		popFolder.open( Folder.READ_WRITE );
		return popFolder;
	}catch(Exception E){
		throw newRunTimeException( E.getMessage() );
	}
}
 
Example 16
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 17
Source File: MailReader.java    From development with Apache License 2.0 4 votes vote down vote up
public String[] readPassAndKeyFromEmail(boolean delete, String userName)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String userPass = null;
    String userKey = null;
    while (retries < 40 && userPass == null) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(MAIL_SUBJECT_USER_ACCOUNT_CREATED_EN)) {
                String content = getMessageContent(message);
                String userNameFromEmail = readInformationFromGivenMail(MAIL_BODY_USERNAME_PATTERN_EN, content);
                if (userName.equals(userNameFromEmail)) {
                    userKey = readInformationFromGivenMail(MAIL_BODY_USERKEY_PATTERN_EN, content);
                    userPass = readInformationFromGivenMail(MAIL_BODY_PASSWORD_PATTERN_EN, content);
                    if (delete) {
                        message.setFlag(Flag.DELETED, true);
                    }
                    break;
                }
            }
        }
        folder.close(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return new String[] {userKey, userPass};
}
 
Example 18
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultFolder() 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("mock_imaps");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    Assert.assertEquals("[INBOX, test]", Arrays.toString(defaultFolder.list()));

    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);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example 19
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 20
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;
}