Sample code for 30+ languages & platforms
Swift 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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    var replacements: Int
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    let statusText = CkoStringBuilder()!
    let statusMatch = CkoJsonObject()!
    var completed: Int
    let token = CkoJsonObject()!
    success = token.loadFile(path: "gmail-mail-token.json")
    if success != true {
        print("Could not load the protocol token from the private working directory.")
        return
    }

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("Authorize or refresh the mailbox first.")
        return
    }

    var mailbox: String? = "user@example.com"
    let imap = CkoImap()!
    imap.ssl = true
    imap.port = 993
    imap.requireSslCertVerify = true
    imap.authMethod = "XOAUTH2"
    success = imap.connect(hostname: "imap.gmail.com")
    if success != true {
        print("Could not establish the Gmail IMAP TLS connection.")
        return
    }

    success = imap.login(login: mailbox, password: token.string(of: "access_token"))
    if success != true {
        imap.disconnect()
        print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
        return
    }

    var capabilities: String? = imap.capability()
    if (imap.lastMethodSuccess != true) || (imap.hasCapability(name: "X-GM-EXT-1", capabilityResponse: capabilities) != true) {
        imap.logout()
        imap.disconnect()
        print("Gmail IMAP extensions are unavailable.")
        return
    }

    success = imap.selectMailbox(mailbox: "INBOX")
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not open INBOX.")
        return
    }

    //  Obtain this decimal string from the Gmail message/thread ID example.
    var gmailMessageId: String? = "1278455344230334865"
    let idText = CkoStringBuilder()!
    idText.append(value: gmailMessageId)
    let validation = CkoJsonObject()!
    var matches: Int = idText.regexMatch(pattern: "\\A[1-9][0-9]{0,19}\\z", json: validation, timeoutMs: 1000).intValue
    if matches != 1 {
        imap.logout()
        imap.disconnect()
        print("Expected a decimal Gmail message ID string.")
        return
    }

    let target = CkoMessageSet()!
    let joined1 = CkoStringBuilder()!
    joined1.append(value: "X-GM-MSGID ")
    joined1.append(value: gmailMessageId)
    success = imap.queryMbx(criteria: joined1.getAsString(), bUid: true, msgSet: target)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not find the Gmail message in the selected mailbox.")
        return
    }

    if target.count.intValue != 1 {
        imap.logout()
        imap.disconnect()
        print("Expected one message in the selected mailbox. Matches: \(target.count.intValue)")
        return
    }

    var uid: String? = target.toCompactString()
    //  Choose read, add, or remove. Only add/remove changes the message.
    var action: String? = "read"
    var label: String? = "Example label"
    if (action != "read") && (action != "add") && (action != "remove") {
        imap.logout()
        imap.disconnect()
        print("Choose read, add, or remove.")
        return
    }

    let labelText = CkoStringBuilder()!
    labelText.append(value: 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(pattern: "\\A[A-Za-z0-9][\\x20-\\x7e]*\\z", json: validation, timeoutMs: 1000).intValue
    if matches != 1 {
        imap.logout()
        imap.disconnect()
        print("Use a printable ASCII custom label starting with a letter or digit.")
        return
    }

    replacements = labelText.replace(value: "\\", replacement: "\\\\").intValue
    replacements = labelText.replace(value: "\"", replacement: "\\\"").intValue
    var response: String?
    var command: String?
    if action != "read" {
        var operation: String? = "+X-GM-LABELS.SILENT"
        if action == "remove" {
            operation = "-X-GM-LABELS.SILENT"
        }

        let joined2 = CkoStringBuilder()!
        joined2.append(value: "UID STORE ")
        joined2.append(value: uid)
        joined2.append(value: " ")
        joined2.append(value: operation)
        joined2.append(value: " (\"")
        joined2.append(value: labelText.getAsString())
        joined2.append(value: "\")")
        command = joined2.getAsString()
        response = imap.sendRawCommand(rawCommand: command)
        statusText.setString(value: response)
        //  A completed raw exchange can still return NO or BAD. Require tagged OK.
        completed = statusText.regexMatch(pattern: "(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", json: statusMatch, timeoutMs: 1000).intValue

        if (imap.lastMethodSuccess != true) || (completed != 1) {
            imap.logout()
            imap.disconnect()
            print("Label update failed. Check the custom label and mailbox permissions.")
            return
        }

    }

    let joined3 = CkoStringBuilder()!
    joined3.append(value: "UID FETCH ")
    joined3.append(value: uid)
    joined3.append(value: " (X-GM-LABELS)")
    response = imap.sendRawCommand(rawCommand: joined3.getAsString())
    statusText.setString(value: response)
    //  A completed raw exchange can still return NO or BAD. Require tagged OK.
    completed = statusText.regexMatch(pattern: "(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", json: statusMatch, timeoutMs: 1000).intValue

    if (imap.lastMethodSuccess != true) || (completed != 1) {
        imap.logout()
        imap.disconnect()
        print("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.
    print("\(response!)")
    imap.logout()
    imap.disconnect()

}