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 Tcl Downloads
load ./chilkat.dll
set success 0
# Assumes Chilkat is unlocked. See Global Unlock Sample.
set key [new_CkJsonObject]
set success [CkJsonObject_LoadFile $key "gmail-service-account.json"]
if {$success != 1} then {
puts "Could not read the service-account JSON key from the private working directory."
delete_CkJsonObject $key
exit
}
if {expr [[CkJsonObject_StringOfEquals $key "type" "service_account" 1] != 1] || [expr [[CkJsonObject_JsonTypeOf $key "private_key"] != 1] || [[CkJsonObject_JsonTypeOf $key "client_email"] != 1]]} then {
puts "Expected a Google service-account JSON key, not an OAuth desktop client file."
delete_CkJsonObject $key
exit
}
set auth [new_CkAuthGoogle]
CkAuthGoogle_put_JsonKey $auth [CkJsonObject_emit $key]
set mailbox "user@example.com"
CkAuthGoogle_put_Scope $auth "https://mail.google.com/"
CkAuthGoogle_put_SubEmailAddress $auth $mailbox
CkAuthGoogle_put_ExpireNumSeconds $auth 3600
# AuthGoogle performs its Google token exchange over this TLS connection.
set connection [new_CkSocket]
CkSocket_put_RequireSslCertVerify $connection 1
set success [CkSocket_Connect $connection "www.googleapis.com" 443 1 10000]
if {$success != 1} then {
puts "Could not establish the Google token connection."
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
exit
}
set success [CkAuthGoogle_ObtainAccessToken $auth $connection]
CkSocket_Close $connection 1000
if {$success != 1} then {
puts "Token exchange failed. Check the key, delegated scope, user, and computer clock."
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
exit
}
# Keep the token in memory. Never print tokens or private keys.
set mailman [new_CkMailMan]
CkMailMan_put_SmtpHost $mailman "smtp.gmail.com"
CkMailMan_put_SmtpPort $mailman 587
CkMailMan_put_SmtpSsl $mailman 0
CkMailMan_put_StartTLS $mailman 1
CkMailMan_put_RequireSslCertVerify $mailman 1
# Alternative: port 465 with SmtpSsl=true and StartTLS=false (implicit TLS).
CkMailMan_put_SmtpUsername $mailman $mailbox
CkMailMan_put_SmtpPassword $mailman ""
CkMailMan_put_OAuth2AccessToken $mailman [CkAuthGoogle_accessToken $auth]
set email [new_CkEmail]
CkEmail_put_From $email $mailbox
CkEmail_put_Subject $email "Sample message"
CkEmail_put_Body $email "This message was sent through Gmail SMTP using OAuth2."
set success [CkEmail_AddTo $email "Recipient" "recipient@example.net"]
if {$success != 1} then {
puts "Could not add the recipient."
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
delete_CkMailMan $mailman
delete_CkEmail $email
exit
}
# This sends a real message. Replace the recipient with an address you control.
set success [CkMailMan_SendEmail $mailman $email]
if {$success != 1} then {
CkMailMan_CloseSmtpConnection $mailman
puts "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.
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
delete_CkMailMan $mailman
delete_CkEmail $email
exit
}
set success [CkMailMan_CloseSmtpConnection $mailman]
if {$success != 1} then {
puts "Gmail accepted the message, but closing the connection failed. Do not resend it."
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
delete_CkMailMan $mailman
delete_CkEmail $email
exit
}
puts "Gmail accepted the message for delivery."
delete_CkJsonObject $key
delete_CkAuthGoogle $auth
delete_CkSocket $connection
delete_CkMailMan $mailman
delete_CkEmail $email