Reputation: 179
I am doing on task to retrieve gmails. I manage to retrieve with below codes. However, it retrieved received email from the earliest to latest emails in the gmail inbox. Is there a way to make it retrieved the latest mails? I intend to implement a way to retrieved the latest 20 mails only instead of retrieved all the mails in the inbox. Thanks in advance for the guidance.
public ArrayList<HashMap<String, String>> getMail(int inboxList){
Folder inbox;
/* Set the mail properties */
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com",username, password);
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
/*Open the inbox using store.*/
inbox.open(Folder.READ_WRITE);
/* Get the messages which is unread in the Inbox*/
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try
{
printAllMessages(messages);
inbox.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
}
catch (NoSuchProviderException e)
{
//e.printStackTrace();
System.exit(1);
}
catch (MessagingException e)
{
//e.printStackTrace();
System.exit(2);
}
Upvotes: 3
Views: 5926
Reputation: 134
Instead of using inbox.search()
use
inbox.getMessages(int start,int end);
it will retrieve the range of messages.
To get the latest 20 mails use:
int n=inbox.getMessageCount();
messages= inbox.getMessages(n-20,n);
Upvotes: 11
Reputation: 29961
If you just want the last 20 messages, just ask for the last 20 message numbers, or access the last 20 entries in the array returned by folder.getMessages(). Not that the order of messages in the mailbox is the order in which they arrived, not the order in which they were sent.
Upvotes: 3
Reputation: 4431
Used the android.os.Message
static class DateCompare implements Comparator<Message> {
public int compare(Message one, Message two){
return one.getWhen().compareTo(two.getWhen());
}
}
............
DateCompare compare = new DateCompare();
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
List<Message> list = Arrays.asList(messages );
Collections.sort(list,compare);
List<Messsage> newList = list.subList(0,19);
hope this helps.
Upvotes: 2