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

Gmail IMAP: Workspace Service Account with a JSON Key

Use a service-account JSON key with Google Workspace domain-wide delegation. A Workspace administrator must authorize the service account's numeric OAuth client ID for https://mail.google.com/. Set SubEmailAddress to the Workspace user whose active Gmail mailbox is being accessed, and use that same address for IMAP login.

A service account has no Gmail mailbox of its own; leaving the impersonated user empty does not grant access to a personal Gmail account. The signed JWT exchange yields a short-lived token without a refresh token. Obtain another when needed, protect the private key, and keep the computer clock accurate.

This example lists visible folders and examines INBOX read-only. For the different visibility rules of the IMAP-only administrative scope, see gmail.imap_admin delegation.

See the Gmail SMTP, IMAP, and POP3 guide for current authentication choices and Gmail-specific examples.

Reference documentation

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    var mailbox: String? = "user@example.com"
    let key = CkoJsonObject()!
    success = key.loadFile(path: "gmail-service-account.json")
    if success != true {
        print("Could not load the private service-account key.")
        return
    }

    if (key.string(ofEquals: "type", value: "service_account", caseSensitive: true) != true) || (key.jsonType(of: "private_key").intValue != 1) {
        print("Expected a Google service-account JSON key.")
        return
    }

    let auth = CkoAuthGoogle()!
    auth.jsonKey = key.emit()
    auth.subEmailAddress = mailbox
    auth.scope = "https://mail.google.com/"
    auth.expireNumSeconds = 3600
    let connection = CkoSocket()!
    connection.requireSslCertVerify = true
    success = connection.connect(hostname: "www.googleapis.com", port: 443, ssl: true, maxWaitMs: 10000)
    if success != true {
        print("Could not establish the Google token connection.")
        return
    }

    success = auth.obtainAccessToken(connection: connection)
    connection.close(maxWaitMs: 1000)
    if success != true {
        print("Check the key, domain-wide delegation client ID/scope, user, and computer clock.")
        return
    }

    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: auth.accessToken)
    if success != true {
        imap.disconnect()
        print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
        return
    }

    let folders = CkoMailboxes()!
    success = imap.mbxList(subscribed: false, reference: "", mbxPattern: "*", mboxes: folders)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not list Gmail folders.")
        return
    }

    //  List the labels visible through ordinary full-mail IMAP access.
    var i: Int = 0
    while (i < folders.count.intValue) {
        print("\(folders.getName(index: i)!)")
        i = i + 1
    }

    success = imap.examineMailbox(mailbox: "INBOX")
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not examine the impersonated user's INBOX.")
        return
    }

    print("INBOX messages: \(imap.numMessages.intValue)")
    imap.logout()
    imap.disconnect()

}