Sample code for 30+ languages & platforms
PowerBuilder

OAuth2 for a GMail using a JSON Service Account Key

See more GMail SMTP/IMAP/POP Examples

This example shows how to obtain an OAuth2 access token for Gmail using a Google Service Account and a JSON private key. Once acquired, the access token can be used to send emails. Remember, upon token expiration, this process needs to be repeated to obtain a new token. Note: This procedure is specific to OAuth2 with Google Service Account keys.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Fac
string ls_JsonKey
oleobject loo_GAuth
oleobject loo_TlsSock
string ls_AccessToken
oleobject loo_Mailman
oleobject loo_Email

li_Success = 0

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

// --------------------------------------------------------------------------------
// 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
// --------------------------------------------------------------------------------

// First load the JSON key into a string.
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")
if li_rc < 0 then
    destroy loo_Fac
    MessageBox("Error","Connecting to COM object failed")
    return
end if
ls_JsonKey = loo_Fac.ReadEntireTextFile("qa_data/googleApi/chilkat25-b4214220e565.json","utf-8")
if loo_Fac.LastMethodSuccess <> 1 then
    Write-Debug loo_Fac.LastErrorText
    destroy loo_Fac
    return
end if

// A Google service account JSON private key looks like this:

// {
//   "type": "service_account",
//   "project_id": "chilkat25",
//   "private_key_id": "b4214220f565881e19eeb97c2699bf5a0d1e3e0b",
//   "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQ...NXcM=\n-----END PRIVATE KEY-----\n",
//   "client_email": "chilkatsvc@chilkat25.iam.gserviceaccount.com",
//   "client_id": "109122032928932715958",
//   "auth_uri": "https://accounts.google.com/o/oauth2/auth",
//   "token_uri": "https://oauth2.googleapis.com/token",
//   "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
//   "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/chilkatsvc%40chilkat25.iam.gserviceaccount.com",
//   "universe_domain": "googleapis.com"
// }

loo_GAuth = create oleobject
li_rc = loo_GAuth.ConnectToNewObject("Chilkat.AuthGoogle")

loo_GAuth.JsonKey = ls_JsonKey

// Specify a scope.
loo_GAuth.Scope = "https://mail.google.com/"

// Request an access token that is valid for this many seconds.
loo_GAuth.ExpireNumSeconds = 3600

// When using a Google Workspace account with Gmail APIs, a service account can impersonate a user 
// via a process called domain-wide delegation � and the "sub" claim in the JWT is what enables this.
// Domain-wide delegation allows a Google Workspace administrator to authorize a service account to 
// act on behalf of any user in the domain, without user interaction.

// This is required for server-to-server access to user data � such as reading/sending Gmail from a background service.
// This is your company email address.
loo_GAuth.SubEmailAddress = "info@chilkat.xyz"

// Connect to www.googleapis.com using TLS
loo_TlsSock = create oleobject
li_rc = loo_TlsSock.ConnectToNewObject("Chilkat.Socket")

li_Success = loo_TlsSock.Connect("www.googleapis.com",443,1,5000)
if li_Success <> 1 then
    Write-Debug loo_TlsSock.LastErrorText
    destroy loo_Fac
    destroy loo_GAuth
    destroy loo_TlsSock
    return
end if

// Send the request to obtain the access token.
li_Success = loo_GAuth.ObtainAccessToken(loo_TlsSock)
if li_Success <> 1 then
    Write-Debug loo_GAuth.LastErrorText
    destroy loo_Fac
    destroy loo_GAuth
    destroy loo_TlsSock
    return
end if

// Examine the access token:
ls_AccessToken = loo_GAuth.AccessToken
Write-Debug "Access Token: " + ls_AccessToken

// Sample output:
// ya29.a0AW4XtxjGTD67Z8 .... IRw0218

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

// -----------------------------------------------------------------------
loo_Mailman = create oleobject
li_rc = loo_Mailman.ConnectToNewObject("Chilkat.MailMan")

// Set the properties for the GMail SMTP server:
loo_Mailman.SmtpHost = "smtp.gmail.com"
loo_Mailman.SmtpPort = 587
loo_Mailman.StartTLS = 1

loo_Mailman.SmtpUsername = "info@chilkat.xyz"
loo_Mailman.OAuth2AccessToken = ls_AccessToken

// Create a new email object
loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")

loo_Email.Subject = "This is a test"
loo_Email.Body = "This is a test"
loo_Email.From = "Chilkat Test <info@chilkat.xyz>"
li_Success = loo_Email.AddTo("Chilkat Software","info@chilkatsoft.com")
// To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

li_Success = loo_Mailman.SendEmail(loo_Email)
if li_Success <> 1 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Fac
    destroy loo_GAuth
    destroy loo_TlsSock
    destroy loo_Mailman
    destroy loo_Email
    return
end if

li_Success = loo_Mailman.CloseSmtpConnection()
if li_Success <> 1 then
    Write-Debug "Connection to SMTP server not closed cleanly."
end if

Write-Debug "Successfully sent email using Gmail with a service account key."


destroy loo_Fac
destroy loo_GAuth
destroy loo_TlsSock
destroy loo_Mailman
destroy loo_Email