Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Apply a Gmail label to search results in batches

See more GMail REST API Examples

Choose a Gmail search query and an existing label name. Resolve the label ID, collect all matching message IDs before changing any labels, then submit at most 1,000 IDs per batchModify call. Empty searches send no updates. For large mailboxes, spool IDs to persistent storage. Completed batches stay applied if a later request fails; adding the same label again is safe.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.StringTable;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        JsonObject token = new JsonObject();
        try {
            token.loadFile("gmail-token.json");
        } catch (ChilkatException e) {
            System.out.println("Could not read gmail-token.json from the private working directory.");
            return;
        }

        if ((token.jsonTypeOf("access_token") != 1) || (token.stringOfEquals("access_token", "", true))) {
            System.out.println("An OAuth access token is required.");
            return;
        }

        Http http = new Http();
        http.setRequireSslCertVerify(true);
        http.setAuthToken(token.stringOf("access_token"));
        HttpResponse resp = new HttpResponse();
        JsonObject reply = new JsonObject();
        try {
            http.httpNoBody("GET", "https://gmail.googleapis.com/gmail/v1/users/me/labels", resp);
            success = true;
        } catch (ChilkatException e) {
            success = false;
        }
        if (resp.getStatusCode() == 0) {
            System.out.println("Gmail did not return an HTTP response.");
            return;
        }

        if ((!success) || ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300))) {
            System.out.println("Gmail HTTP " + resp.getStatusCode());
            try {
                reply.load(resp.getBodyStr());
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                System.out.println(reply.stringOf("error.message"));
            }

            return;
        }

        try {
            reply.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Expected a Gmail JSON response.");
            return;
        }

        if (reply.jsonTypeOf("labels") != 4) {
            System.out.println("Expected a list of labels.");
            return;
        }

        JsonObject label = new JsonObject();
        try {
            reply.findRecord2("labels", "name", "To review", true, label);
        } catch (ChilkatException e) {
            System.out.println("No label with that exact name. Check the name or create the label first.");
            return;
        }

        StringBuilder labelId = new StringBuilder();
        try {
            label.stringOfSb("id", labelId);
        } catch (ChilkatException e) {
            System.out.println("Could not read the label ID.");
            return;
        }

        StringTable ids = new StringTable();
        StringBuilder baseUrl = new StringBuilder();
        baseUrl.append("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500");
        String searchQuery = "has:attachment";
        baseUrl.append("&q=");
        baseUrl.append(http.urlEncode(searchQuery));
        StringBuilder url = new StringBuilder();
        StringBuilder pageToken = new StringBuilder();
        boolean more = true;
        while (more) {
            url.setString(baseUrl.getAsString());
            if (pageToken.getLength() > 0) {
                url.append("&pageToken=");
                url.append(http.urlEncode(pageToken.getAsString()));
            }

            try {
                http.httpNoBody("GET", url.getAsString(), resp);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (resp.getStatusCode() == 0) {
                System.out.println("Gmail did not return an HTTP response.");
                return;
            }

            if ((!success) || ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300))) {
                System.out.println("Gmail HTTP " + resp.getStatusCode());
                try {
                    reply.load(resp.getBodyStr());
                    success = true;
                } catch (ChilkatException e) {
                    success = false;
                }
                if (success) {
                    System.out.println(reply.stringOf("error.message"));
                }

                return;
            }

            try {
                reply.load(resp.getBodyStr());
            } catch (ChilkatException e) {
                System.out.println("Expected a Gmail JSON response.");
                return;
            }

            // Gmail can omit messages when the search or mailbox is empty.
            int count = reply.sizeOfArray("messages");
            int i = 0;
            while (i < count) {
                reply.setI(i);
                try {
                    ids.append(reply.stringOf("messages[i].id"));
                } catch (ChilkatException e) {
                    System.out.println("Could not retain a message ID.");
                    return;
                }

                i = i + 1;
            }

            more = false;
            if (reply.jsonTypeOf("nextPageToken") == 1) {
                pageToken.setString(reply.stringOf("nextPageToken"));
                more = pageToken.getLength() > 0;
            }
        }

        // Search is complete. Apply the label to each group and track confirmed progress.
        JsonObject request = new JsonObject();
        int done = 0;
        while (done < ids.getCount()) {
            request.clear();
            request.updateString("addLabelIds[0]", labelId.getAsString());
            int n = 0;
            while ((n < 1000) && ((done + n) < ids.getCount())) {
                request.setI(n);
                request.updateString("ids[i]", ids.stringAt(done + n));
                n = n + 1;
            }

            try {
                http.httpJson("POST", "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify", request, "application/json", resp);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (resp.getStatusCode() == 0) {
                System.out.println("Gmail did not return an HTTP response.");
                return;
            }

            if ((!success) || ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300))) {
                System.out.println("Gmail HTTP " + resp.getStatusCode());
                try {
                    reply.load(resp.getBodyStr());
                    success = true;
                } catch (ChilkatException e) {
                    success = false;
                }
                if (success) {
                    System.out.println(reply.stringOf("error.message"));
                }

                return;
            }

            done = done + n;
            System.out.println("Messages labeled so far: " + done);
        }

        System.out.println("Total messages labeled: " + done);
    }
}