AutoIt
AutoIt
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 AutoIt Downloads
Local $bSuccess = False
; This example requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.
$oHttp = ObjCreate("Chilkat.Http")
; --------------------------------------------------------------------------------
; 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)
$oCert = ObjCreate("Chilkat.Cert")
$bSuccess = $oCert.LoadPfxFile("c:/someDirectory/keys/chilkat25-cbd7b42afbd8.p12","notasecret")
If ($bSuccess <> True) Then
ConsoleWrite($oCert.LastErrorText & @CRLF)
Exit
EndIf
; The ISS is your service account email address ending in gserviceaccount.com.
Local $sIss = "chilkatsvc@chilkat25.iam.gserviceaccount.com"
; The scope is always the following string:
Local $scope = "https://mail.google.com/"
; The sub is your company email address
Local $sOauth_sub = "bob@yourcompany.com"
; The access token is valid for this number of seconds.
Local $iNumSec = 3600
Local $sAccessToken = $oHttp.G_SvcOauthAccessToken($sIss,$scope,$sOauth_sub,$iNumSec,$oCert)
If ($oHttp.LastMethodSuccess <> True) Then
ConsoleWrite($oHttp.LastErrorText & @CRLF)
Exit
Else
ConsoleWrite("access token: " & $sAccessToken & @CRLF)
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.
; -----------------------------------------------------------------------
$oMailman = ObjCreate("Chilkat.MailMan")
; Set the properties for the GMail SMTP server:
$oMailman.SmtpHost = "smtp.gmail.com"
$oMailman.SmtpPort = 587
$oMailman.StartTLS = True
$oMailman.SmtpUsername = "bob@yourcompany.com"
$oMailman.OAuth2AccessToken = $sAccessToken
; Create a new email object
$oEmail = ObjCreate("Chilkat.Email")
$oEmail.Subject = "This is a test"
$oEmail.Body = "This is a test"
$oEmail.From = "Bob <bob@yourcompany.com>"
$bSuccess = $oEmail.AddTo("Recipient","recipient@example.com")
; To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.
$bSuccess = $oMailman.SendEmail($oEmail)
If ($bSuccess <> True) Then
ConsoleWrite($oMailman.LastErrorText & @CRLF)
Exit
EndIf
$bSuccess = $oMailman.CloseSmtpConnection()
If ($bSuccess <> True) Then
ConsoleWrite("Connection to SMTP server not closed cleanly." & @CRLF)
EndIf
ConsoleWrite("Successfully sent email using Gmail with a service account key." & @CRLF)