Lianja
Lianja
OAuth2 for a GMail using a P12 Service Account Key
See more GMail REST API Examples
Demonstrates how to use GMail with OAuth2 for aservice 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 Lianja Downloads
llSuccess = .F.
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
loHttp = createobject("CkHttp")
// --------------------------------------------------------------------------------
// 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)
loCert = createobject("CkCert")
llSuccess = loCert.LoadPfxFile("c:/someDirectory/keys/chilkat25-cbd7b42afbd8.p12","notasecret")
if (llSuccess <> .T.) then
? loCert.LastErrorText
release loHttp
release loCert
return
endif
// The ISS is your service account email address ending in gserviceaccount.com.
lcIss = "chilkatsvc@chilkat25.iam.gserviceaccount.com"
// The scope is always the following string:
lcScope = "https://mail.google.com/"
// The sub is your company email address
lcOauth_sub = "bob@yourcompany.com"
// The access token is valid for this number of seconds.
lnNumSec = 3600
lcAccessToken = loHttp.G_SvcOauthAccessToken(lcIss,lcScope,lcOauth_sub,lnNumSec,loCert)
if (loHttp.LastMethodSuccess <> .T.) then
? loHttp.LastErrorText
release loHttp
release loCert
return
else
? "access token: " + lcAccessToken
endif
// The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.
// -----------------------------------------------------------------------
loMailman = createobject("CkMailMan")
// Set the properties for the GMail SMTP server:
loMailman.SmtpHost = "smtp.gmail.com"
loMailman.SmtpPort = 587
loMailman.StartTLS = .T.
loMailman.SmtpUsername = "bob@yourcompany.com"
loMailman.OAuth2AccessToken = lcAccessToken
// Create a new email object
loEmail = createobject("CkEmail")
loEmail.Subject = "This is a test"
loEmail.Body = "This is a test"
loEmail.From = "Bob <bob@yourcompany.com>"
llSuccess = loEmail.AddTo("Recipient","recipient@example.com")
// To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.
llSuccess = loMailman.SendEmail(loEmail)
if (llSuccess <> .T.) then
? loMailman.LastErrorText
release loHttp
release loCert
release loMailman
release loEmail
return
endif
llSuccess = loMailman.CloseSmtpConnection()
if (llSuccess <> .T.) then
? "Connection to SMTP server not closed cleanly."
endif
? "Successfully sent email using Gmail with a service account key."
release loHttp
release loCert
release loMailman
release loEmail