Javamail奇怪的行为

时间:2014-01-28 05:43:51

标签: java junit tomcat7 javamail

Javamail在JUnit测试和GlassFish 3.1.2中工作正常,但在Tomcat 7.0.41中不起作用:所有“From”标题都为NULL! 我究竟做错了什么? 当我用代码运行JUnit测试时:

        @Test
        public void emailTest() {

            try {

                Properties properties = new Properties();
                properties.put("mail.pop3.host", EMAILUtil.POP3_HOST);
                properties.put("mail.pop3.disabletop", true);

                Store emailStore = Session.getDefaultInstance(properties).getStore(EMAILUtil.STORE_TYPE);
                emailStore.connect(EMAILUtil.USER, EMAILUtil.PASSWORD);

                Folder emailFolder = emailStore.getFolder(EMAILUtil.DEFAULT_FOLDER);
                emailFolder.open(Folder.READ_WRITE);
                Message[] messages = emailFolder.getMessages();

                System.out.println("Message count: " + messages.length);

                int errorCount = 0;

                for (int i = 0, n = messages.length; i < n; i++) {
                   System.out.println("Message: " + messages[i].toString());
                   System.out.println("From: " + messages[i].getFrom());
                }

                emailFolder.close(true);
                emailStore.close();

            } catch (MessagingException ex) {
                System.out.println("Readings mails Exception: " + ex.getMessage());
                ex.printStackTrace(System.err);
            }        

        }

我得到了正确的结果(与GlassFish3结果相同):

 Message count: 406
 Message: com.sun.mail.pop3.POP3Message@167a
 From: [Ljavax.mail.internet.InternetAddress;@f9ead4
 Message: com.sun.mail.pop3.POP3Message@72f580
 From: [Ljavax.mail.internet.InternetAddress;@153b61e

当我在Tomcat7上运行此代码时,我得到以下结果(所有“From”标题为null):

 Message count: 406
 Message: com.sun.mail.pop3.POP3Message@95acf2
 From: null
 Message: com.sun.mail.pop3.POP3Message@a38f9f
 From: null

任何人都可以帮助解决这个问题吗? JUnit版本:4.5 Javamail版本:1.4.4(我也尝试使用1.5.5,结果相同)

1 个答案:

答案 0 :(得分:1)

添加properties.put(“mail.debug”,“true”);并比较两种情况下的调试输出。

另外,尝试将Session.getDefaultInstance更改为Session.getInstance。