Gmail SMTP: Workspace Service Account with a JSON Key
See more GMail SMTP/IMAP/POP Examples
Obtain a short-lived OAuth2 token for a Google Workspace user's mailbox, then send email using Gmail SMTP. This requires a Workspace administrator to authorize the service account's numeric OAuth client ID for https://mail.google.com/ in domain-wide delegation. Enable domain-wide delegation for the service account and impersonate a user with an active Gmail mailbox.
This is a signed JWT bearer grant with user impersonation, not an OAuth client-credentials grant. A service account has no Gmail mailbox of its own. This approach does not provide delegated access to personal @gmail.com accounts. Protect the private key and restrict who can run the application; anyone with this key can exercise its delegated privileges.
Set SubEmailAddress and the SMTP username to the same Workspace mailbox. Keep the computer clock accurate. The token lasts at most one hour and has no refresh token: obtain a new delegated token when needed. Gmail's normal sending limits still apply; delegation does not permit unlimited sending.
Send an email through smtp.gmail.com:587 with STARTTLS and an OAuth2 access token. Chilkat constructs the SASL XOAUTH2 authentication exchange; do not put the access token in SmtpPassword. Port 465 with implicit TLS is an alternative.
This example sends a real email. Set the mailbox to the account that authorized the token and use a recipient you control. The From address is that mailbox; another address must be an authorized Gmail send-as identity. Gmail normally saves SMTP submissions in Sent, so do not automatically append another copy through IMAP.
SMTP acceptance does not prove inbox delivery. Account sending limits, recipient limits, spam filtering, and Workspace policies still apply. A connection failure after message data was transmitted can leave the result uncertain; blind retries can create duplicate mail. Authentication/session logs can contain credentials and message data.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Key
oleobject loo_Auth
string ls_Mailbox
oleobject loo_Connection
oleobject loo_Mailman
oleobject loo_Email
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
loo_Key = create oleobject
li_rc = loo_Key.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Key
MessageBox("Error","Connecting to COM object failed")
return
end if
li_Success = loo_Key.LoadFile("gmail-service-account.json")
if li_Success <> 1 then
Write-Debug "Could not read the service-account JSON key from the private working directory."
destroy loo_Key
return
end if
if (loo_Key.StringOfEquals("type","service_account",1) <> 1) OR (loo_Key.JsonTypeOf("private_key") <> 1) OR (loo_Key.JsonTypeOf("client_email") <> 1) then
Write-Debug "Expected a Google service-account JSON key, not an OAuth desktop client file."
destroy loo_Key
return
end if
loo_Auth = create oleobject
li_rc = loo_Auth.ConnectToNewObject("Chilkat.AuthGoogle")
loo_Auth.JsonKey = loo_Key.Emit()
ls_Mailbox = "user@example.com"
loo_Auth.Scope = "https://mail.google.com/"
loo_Auth.SubEmailAddress = ls_Mailbox
loo_Auth.ExpireNumSeconds = 3600
// AuthGoogle performs its Google token exchange over this TLS connection.
loo_Connection = create oleobject
li_rc = loo_Connection.ConnectToNewObject("Chilkat.Socket")
loo_Connection.RequireSslCertVerify = 1
li_Success = loo_Connection.Connect("www.googleapis.com",443,1,10000)
if li_Success <> 1 then
Write-Debug "Could not establish the Google token connection."
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
return
end if
li_Success = loo_Auth.ObtainAccessToken(loo_Connection)
loo_Connection.Close(1000)
if li_Success <> 1 then
Write-Debug "Token exchange failed. Check the key, delegated scope, user, and computer clock."
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
return
end if
// Keep the token in memory. Never print tokens or private keys.
loo_Mailman = create oleobject
li_rc = loo_Mailman.ConnectToNewObject("Chilkat.MailMan")
loo_Mailman.SmtpHost = "smtp.gmail.com"
loo_Mailman.SmtpPort = 587
loo_Mailman.SmtpSsl = 0
loo_Mailman.StartTLS = 1
loo_Mailman.RequireSslCertVerify = 1
// Alternative: port 465 with SmtpSsl=true and StartTLS=false (implicit TLS).
loo_Mailman.SmtpUsername = ls_Mailbox
loo_Mailman.SmtpPassword = ""
loo_Mailman.OAuth2AccessToken = loo_Auth.AccessToken
loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")
loo_Email.From = ls_Mailbox
loo_Email.Subject = "Sample message"
loo_Email.Body = "This message was sent through Gmail SMTP using OAuth2."
li_Success = loo_Email.AddTo("Recipient","recipient@example.net")
if li_Success <> 1 then
Write-Debug "Could not add the recipient."
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
destroy loo_Mailman
destroy loo_Email
return
end if
// This sends a real message. Replace the recipient with an address you control.
li_Success = loo_Mailman.SendEmail(loo_Email)
if li_Success <> 1 then
loo_Mailman.CloseSmtpConnection()
Write-Debug "SMTP send failed. Check the token, mailbox, recipient, and Gmail sending limits."
// Inspect LastErrorText privately if needed; do not publish authentication/session logs.
// A lost connection after DATA can leave acceptance uncertain. Avoid blindly retrying.
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
destroy loo_Mailman
destroy loo_Email
return
end if
li_Success = loo_Mailman.CloseSmtpConnection()
if li_Success <> 1 then
Write-Debug "Gmail accepted the message, but closing the connection failed. Do not resend it."
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
destroy loo_Mailman
destroy loo_Email
return
end if
Write-Debug "Gmail accepted the message for delivery."
destroy loo_Key
destroy loo_Auth
destroy loo_Connection
destroy loo_Mailman
destroy loo_Email