D 的个人博客

但行好事莫问前程

  menu
417 文章
3446695 浏览
3 当前访客
ღゝ◡╹)ノ❤️

JavaMail 读取 Gmail 邮件的问题

最近在写JavaMail接收Gmail邮件的NetBeans插件,发现一个问题。。。。

下面是连接邮件账户与接收邮件的代码片断:

 /** 
     * conncect to the gmail account.
     * 
@param userName user name
     * 
@param userPassword user password
     * 
@throws Exception
     
*/
    
private static void connect(String userName, String userPassword)
            
throws Exception {
        Security.addProvider(
new com.sun.net.ssl.internal.ssl.Provider());
        
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties props 
= System.getProperties();
        props.setProperty(
"mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty(
"mail.pop3.socketFactory.fallback""false");
        props.setProperty(
"mail.pop3.port""995");
        props.setProperty(
"mail.pop3.socketFactory.port""995");

        props.setProperty(
"mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty(
"mail.imap.socketFactory.fallback""false");
        props.setProperty(
"mail.imap.port""993");
        props.setProperty(
"mail.imap.socketFactory.port""993");


        Session session 
= Session.getDefaultInstance(props, null);
        session.setDebug(
true); // set debug

//        URLName urln = new URLName("pop3s", "pop.gmail.com", 995, null,
//                userName, userPassword);
        URLName urln = new URLName("imap""imap.gmail.com"993null, userName,
                userPassword);
        store 
= session.getStore(urln);
        store.connect();
    }

    
/**
     * Retieve all new messages.
     * 
@param userName user name
     * 
@param userPassword user password
     * 
@return all new messages
     * 
@throws Exception
     
*/
    
public Message[] getNewMails(String userName, String userPassword)
            
throws Exception {
        
if (!store.isConnected()) {
            connect(userName, userPassword);
        }

        Folder inbox 
= store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        FetchProfile profile 
= new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);

        
if (inbox.getUnreadMessageCount() > 0) {
            
int fetchCount = inbox.getMessageCount() - inbox.getUnreadMessageCount();
            
if (fetchCount == 0) {
                
return inbox.getMessages();
            }

            Message[] messages 
= inbox.getMessages(12);


            
return messages;
        } 
else {
            System.out.println(
"No any new mail!");
            
throw new RuntimeException("No any new mail!");
        }
    }

使用POP3/POP3s连接后统计出来的邮件数目都是不对的。而使用IMAP统计的就正确了。很郁闷。。。。