Skip to content Skip to sidebar Skip to footer

Get Last 20 Emails From Gmail (java Android)

How can I get last 20 emails from gmail? ListMessagesResponse listMessagesResponse = mService.users().messages() .list(user).setQ('from:----')

Solution 1:

As @trajchevska pointed out you can only get the basic details with your code. To get messages in full format you should call mService.users().messages().get(user, messageId).execute() for every message. Best way for this is to create a batch call. So if you want to get all the messages that match specified query you should do something like this.

finalListMessagesResponseresponse= mService.users().messages().list(user).setQ("from:----").execute();
final List<Message> messages = newArrayList<Message>();
while (response.getMessages() != null) {
    messages.addAll(response.getMessages());
    if (response.getNextPageToken() != null) {
        StringpageToken= response.getNextPageToken();
        response = service.users().messages().list(user).setQ("from:----").setPageToken(pageToken).execute();
    } else {
        break;
    }
}

final List<Message> fullMessages = newArrayList<>();
final JsonBatchCallback<Message> callback = newJsonBatchCallback<Message>() {
    publicvoidonSuccess(Message message, HttpHeaders responseHeaders) {
        fullMessages.add(message);
    }

    publicvoidonFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
        // do what you want if error occurs
    }
};
BatchRequestbatch= mService.batch();
for (Message message : messages) {
    mService.users().messages().get(user, message.getId()).setFormat("full").queue(batch, callback);
}

batch.execute();

Hope this helps.

Solution 2:

The list function only returns the list of messages with basic details which is usually the id only. If you want to get the payload or other message details you need to iterate through all messages pulled with list and call the wanted function specifically on the selected object. I only have some basic knowledge in Java, but the logic would be something like this:

messages = listMessagesResponse.getMessages();
for (Message message : messages) {
  payload = message.getPayload();
  ...
}

Check their docs, they have some example that can be helpful.

List Messages

Get Concrete Message

Post a Comment for "Get Last 20 Emails From Gmail (java Android)"