我是JavaMail API的新手,目前正在从Tutorialspoint学习。现在我可以使用以下代码从我的邮件中获取所有电子邮件
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password)
{
try {
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "yourmail@gmail.com";// change accordingly
String password = "*****";// change accordingly
check(host, mailStoreType, username, password);
}
}
所以现在我在输出中收到整个邮件,因为**我正在使用条件i&lt; message.length **
我想要的是我只想阅读20条消息并将其显示在jtable中然后如果我想要更多,那么只阅读下一条20条消息,依此类推。我怎么能这样做?
我正在考虑用i&lt;创建一个循环。 20但接下来的20呢?如何阅读接下来的20封邮件,不再从开始阅读邮件???
答案 0 :(得分:5)
javax.mail.Folder上有一个方法,允许您从开始/结束检索消息。您只需要跟踪您从中检索的最后位置。
public Message[] getMessages(int start,
int end)
throws MessagingException
Get the Message objects for message numbers ranging from start through end, both start and end inclusive. Note that message numbers start at 1, not 0.
Message objects are light-weight references to the actual message that get filled up on demand. Hence Folder implementations are expected to provide light-weight Message objects.
This implementation uses getMessage(index) to obtain the required Message objects. Note that the returned array must contain (end-start+1) Message objects.
Parameters:
start - the number of the first message
end - the number of the last message
Returns:
the Message objects
Throws:
FolderNotFoundException - if this folder does not exist.
IllegalStateException - if this folder is not opened.
java.lang.IndexOutOfBoundsException - if the start or end message numbers are out of range.
MessagingException