Sample code for 30+ languages & platforms
CkJava Requires Chilkat v11.1.0+

Gmail IMAP: Read, Add, or Remove Message Labels

See more GMail SMTP/IMAP/POP Examples

Locate a message in INBOX by its decimal Gmail message ID, then read its labels or add/remove one custom label with X-GM-LABELS. The default action is read. Changing action to add or remove modifies the mailbox. Obtain the message ID from the message and thread IDs example.

The code changes only the specified custom label and preserves other labels. A message shown under several labels is still one Gmail message. System labels have different semantics; use the archive/Trash example for those operations. If the message left INBOX, select its current mailbox before searching.

This focused raw-command example accepts printable ASCII custom labels beginning with a letter or digit, escapes quotes and backslashes, and displays the returned label list in IMAP syntax. Non-ASCII names require IMAP modified UTF-7 encoding. The response is not parsed by splitting on spaces because quoted names can contain spaces.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

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

    int replacements;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkStringBuilder statusText = new CkStringBuilder();
    CkJsonObject statusMatch = new CkJsonObject();
    int completed;
    CkJsonObject token = new CkJsonObject();
    success = token.LoadFile("gmail-mail-token.json");
    if (success != true) {
        System.out.println("Could not load the protocol token from the private working directory.");
        return;
        }

    if ((token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true)) {
        System.out.println("Authorize or refresh the mailbox first.");
        return;
        }

    String mailbox = "user@example.com";
    CkImap imap = new CkImap();
    imap.put_Ssl(true);
    imap.put_Port(993);
    imap.put_RequireSslCertVerify(true);
    imap.put_AuthMethod("XOAUTH2");
    success = imap.Connect("imap.gmail.com");
    if (success != true) {
        System.out.println("Could not establish the Gmail IMAP TLS connection.");
        return;
        }

    success = imap.Login(mailbox,token.stringOf("access_token"));
    if (success != true) {
        imap.Disconnect();
        System.out.println("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.");
        return;
        }

    String capabilities = imap.capability();
    if ((imap.get_LastMethodSuccess() != true) || (imap.HasCapability("X-GM-EXT-1",capabilities) != true)) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Gmail IMAP extensions are unavailable.");
        return;
        }

    success = imap.SelectMailbox("INBOX");
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Could not open INBOX.");
        return;
        }

    //  Obtain this decimal string from the Gmail message/thread ID example.
    String gmailMessageId = "1278455344230334865";
    CkStringBuilder idText = new CkStringBuilder();
    idText.Append(gmailMessageId);
    CkJsonObject validation = new CkJsonObject();
    int matches = idText.RegexMatch("\\A[1-9][0-9]{0,19}\\z",validation,1000);
    if (matches != 1) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Expected a decimal Gmail message ID string.");
        return;
        }

    CkMessageSet target = new CkMessageSet();
    CkStringBuilder joined1 = new CkStringBuilder();
    joined1.Append("X-GM-MSGID ");
    joined1.Append(gmailMessageId);
    success = imap.QueryMbx(joined1.getAsString(),true,target);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Could not find the Gmail message in the selected mailbox.");
        return;
        }

    if (target.get_Count() != 1) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Expected one message in the selected mailbox. Matches: " + target.get_Count());
        return;
        }

    String uid = target.toCompactString();
    //  Choose read, add, or remove. Only add/remove changes the message.
    String action = "read";
    String label = "Example label";
    if ((action != "read") && (action != "add") && (action != "remove")) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Choose read, add, or remove.");
        return;
        }

    CkStringBuilder labelText = new CkStringBuilder();
    labelText.Append(label);
    //  This raw-command example accepts printable ASCII custom labels only.
    //  For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
    matches = labelText.RegexMatch("\\A[A-Za-z0-9][\\x20-\\x7e]*\\z",validation,1000);
    if (matches != 1) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Use a printable ASCII custom label starting with a letter or digit.");
        return;
        }

    replacements = labelText.Replace("\\","\\\\");
    replacements = labelText.Replace("\"","\\\"");
    String response;
    String command;
    if (action != "read") {
        String operation = "+X-GM-LABELS.SILENT";
        if (action == "remove") {
            operation = "-X-GM-LABELS.SILENT";
            }

        CkStringBuilder joined2 = new CkStringBuilder();
        joined2.Append("UID STORE ");
        joined2.Append(uid);
        joined2.Append(" ");
        joined2.Append(operation);
        joined2.Append(" (\"");
        joined2.Append(labelText.getAsString());
        joined2.Append("\")");
        command = joined2.getAsString();
        response = imap.sendRawCommand(command);
        statusText.SetString(response);
        //  A completed raw exchange can still return NO or BAD. Require tagged OK.
        completed = statusText.RegexMatch("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",statusMatch,1000);

        if ((imap.get_LastMethodSuccess() != true) || (completed != 1)) {
            imap.Logout();
            imap.Disconnect();
            System.out.println("Label update failed. Check the custom label and mailbox permissions.");
            return;
            }

        }

    CkStringBuilder joined3 = new CkStringBuilder();
    joined3.Append("UID FETCH ");
    joined3.Append(uid);
    joined3.Append(" (X-GM-LABELS)");
    response = imap.sendRawCommand(joined3.getAsString());
    statusText.SetString(response);
    //  A completed raw exchange can still return NO or BAD. Require tagged OK.
    completed = statusText.RegexMatch("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",statusMatch,1000);

    if ((imap.get_LastMethodSuccess() != true) || (completed != 1)) {
        imap.Logout();
        imap.Disconnect();
        System.out.println("Could not read the message labels.");
        return;
        }

    //  Display the server's label-list syntax, including quoted/encoded names.
    //  This is a FETCH response, not an authentication/session log.
    System.out.println(response);
    imap.Logout();
    imap.Disconnect();
  }
}