Sample code for 30+ languages & platforms
Swift

OAuth2 for a GMail using a P12 Service Account Key

See more GMail REST API Examples

Demonstrates how to use GMail with OAuth2 for a service account within a Google Workspace Account where your email domain is custom (e.g., @yourcompany.com).

Note: This example does not work for Personal Google Accounts where the email domain is @gmail.com

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    // --------------------------------------------------------------------------------
    // For a step-by-step guide for setting up your Google Workspace service account,
    // see Setup Google Workspace Account for Sending SMTP GMail from a Service Account
    // --------------------------------------------------------------------------------
    // Begin by loading your Google service account key (.p12)
    let cert = CkoCert()!
    success = cert.loadPfxFile(path: "c:/someDirectory/keys/chilkat25-cbd7b42afbd8.p12", password: "notasecret")
    if success != true {
        print("\(cert.lastErrorText!)")
        return
    }

    // The ISS is your service account email address ending in gserviceaccount.com.
    var iss: String? = "chilkatsvc@chilkat25.iam.gserviceaccount.com"

    // The scope is always the following string:
    var scope: String? = "https://mail.google.com/"

    // The sub is your company email address
    var oauth_sub: String? = "bob@yourcompany.com"

    // The access token is valid for this number of seconds.
    var numSec: Int = 3600

    var accessToken: String? = http.g_SvcOauthAccessToken(iss: iss, scope: scope, subEmail: oauth_sub, numSec: numSec, cert: cert)
    if http.lastMethodSuccess != true {
        print("\(http.lastErrorText!)")
        return
    }
    else {
        print("access token: \(accessToken!)")
    }

    // The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.

    // -----------------------------------------------------------------------
    let mailman = CkoMailMan()!

    // Set the properties for the GMail SMTP server:
    mailman.smtpHost = "smtp.gmail.com"
    mailman.smtpPort = 587
    mailman.startTLS = true

    mailman.smtpUsername = "bob@yourcompany.com"
    mailman.oAuth2AccessToken = accessToken

    // Create a new email object
    let email = CkoEmail()!

    email.subject = "This is a test"
    email.body = "This is a test"
    email.from = "Bob <bob@yourcompany.com>"
    success = email.add(to: "Recipient", emailAddress: "recipient@example.com")
    // To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

    success = mailman.sendEmail(email: email)
    if success != true {
        print("\(mailman.lastErrorText!)")
        return
    }

    success = mailman.closeSmtpConnection()
    if success != true {
        print("Connection to SMTP server not closed cleanly.")
    }

    print("Successfully sent email using Gmail with a service account key.")

}