java获取邮件的未读或已读状态
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import
javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class GetUnReadMail {
/**
* @param args
*/
private static String protocol="pop3"; //服务协议
private static String mailHost="pop.126.com"; //服务器地址
private static String userName="******"; //用户名
private static String password="******"; //密码
public static void main(String[] args) {
// TODO Auto-generated method stub
Store store = null;
try{
Session session = Session.getDefaultInstance(System.getProperties(),null);
//创建store,建立连接
store = session.getStore(protocol);
System.out.println("连接中......");
store.connect(mailHost, userName, password);
System.out.println("连接成功!");
}catch(Exception e){
System.err.println("创建Store失败!");
e.printStackTrace();
}
Folder getFolder=null;
try{
getFolder = store.getFolder("INBOX");
getFolder.open(Folder.READ_ONLY);
System.out.println("新邮件个数:"+getFolder.getNewMessageCount());
System.out.println("未读邮件个数:"+getFolder.getUnreadMessageCount());
System.out.println("所有邮件个数:"+getFolder.getMessageCount());
}catch (
MessagingException e){
// TODO Auto-generated catch block
System.err.println("获取Folder失败!");
e.printStackTrace();
}
try {
Message[] messages = getFolder.getMessages();
for(int i=0;i<messages.length;i++){
Flags flags = messages[i].getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for (int j = 0; j < flag.length; i++){
if (flag[j] == Flags.Flag.SEEN){
System.out.println(flag[j]);
}
}
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (getFolder.isOpen())
try {
getFolder.close(true);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行得到的结果:
连接中......
连接成功!
新邮件个数:0
未读邮件个数:15
所有邮件个数:15
所有邮件的个数是正确的,可是未读邮件有3封,新邮件也是三封,结果为什么会显示这样呢,大侠们帮帮忙!
------解决方案--------------------你用户名 密码 mailhost 封装到 properties 试下
Properties prop = System.getProperties();
prop.put("mail.store.protocol", "imap");
prop.put("mail.imap.host", "imap.163.com");
Session session = Session.getInstance(prop);
int total = 0;
IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
store.connect(user, password);
------解决方案--------------------o(╯□╰)o 问题都一年多了
------解决方案--------------------imap协议才支持未读已读的邮件区分
------解决方案--------------------我擦 一年前的问题