Gmail SMTP, IMAP, and POP3: Obtain an OAuth2 Token
See more OAuth2 Examples
Obtain a Gmail OAuth2 access token and an offline refresh token for a desktop application using the system browser and a loopback listener. This one authorization works with SMTP, IMAP, and POP3 for the same account; a separate consent flow for each protocol is unnecessary.
In Google Cloud, configure the consent screen and create an OAuth client of type Desktop app. Supply that client's ID and secret. Add the account as a test user while an external app is in Testing. Desktop clients are public clients: an embedded client secret is not a reliable secret. This example uses PKCE with S256 and Chilkat's authorization state handling. The browser and application must run on the same computer; this is not a web-backend redirect handler.
access_type=offline requests a refresh token; prompt=consent is used for this initial setup. Subsequent runs should refresh the saved grant instead of prompting every time. The checked file write saves gmail-mail-token.json in a private working directory without printing credentials. Use one cache per account and OAuth client. Applications with concurrent jobs should serialize and atomically replace cache files.
For an external application in Testing, a refresh token with the mail scope normally expires after seven days. Revocation, account password changes, and organization policies can also require fresh authorization. An access token is short-lived; use its expires_in and the saved UTC obtained_at, allowing a clock margin, to schedule refresh.
Gmail SMTP, IMAP, and POP3 use the https://mail.google.com/ OAuth scope. Narrower Gmail REST scopes such as gmail.send or gmail.readonly do not authorize these protocols. Public applications using this restricted scope must meet Google's verification requirements. See Gmail OAuth scopes and XOAUTH2.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Oauth
string ls_AuthUrl
long li_Waited
oleobject loo_Token
oleobject loo_Obtained
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
loo_Oauth = create oleobject
li_rc = loo_Oauth.ConnectToNewObject("Chilkat.OAuth2")
if li_rc < 0 then
destroy loo_Oauth
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_Oauth.TokenEndpoint = "https://oauth2.googleapis.com/token"
loo_Oauth.ClientId = "YOUR_DESKTOP_CLIENT_ID"
loo_Oauth.ClientSecret = "YOUR_DESKTOP_CLIENT_SECRET"
loo_Oauth.AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth"
loo_Oauth.LocalHost = "127.0.0.1"
loo_Oauth.ListenPort = 55568
loo_Oauth.ListenPortRangeEnd = 55578
loo_Oauth.CodeChallenge = 1
loo_Oauth.CodeChallengeMethod = "S256"
loo_Oauth.Scope = "https://mail.google.com/"
li_Success = loo_Oauth.AddAuthQueryParam("access_type","offline")
if li_Success <> 1 then
Write-Debug "Could not configure offline access."
destroy loo_Oauth
return
end if
// This is the interactive setup step. Subsequent refreshes use the saved refresh token.
li_Success = loo_Oauth.AddAuthQueryParam("prompt","consent")
if li_Success <> 1 then
Write-Debug "Could not configure consent."
destroy loo_Oauth
return
end if
ls_AuthUrl = loo_Oauth.StartAuth()
if loo_Oauth.LastMethodSuccess <> 1 then
Write-Debug "Could not start the loopback listener."
destroy loo_Oauth
return
end if
li_Success = loo_Oauth.LaunchBrowser(ls_AuthUrl)
if li_Success <> 1 then
loo_Oauth.Cancel()
Write-Debug "Could not open the system browser."
destroy loo_Oauth
return
end if
li_Waited = 0
do while ((loo_Oauth.AuthFlowState < 3) AND (li_Waited < 180000))
loo_Oauth.SleepMs(200)
li_Waited = li_Waited + 200
loop
if loo_Oauth.AuthFlowState < 3 then
loo_Oauth.Cancel()
Write-Debug "Authorization timed out."
destroy loo_Oauth
return
end if
if loo_Oauth.AuthFlowState <> 3 then
Write-Debug "Authorization did not complete. Flow state: " + string(loo_Oauth.AuthFlowState)
destroy loo_Oauth
return
end if
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
li_Success = loo_Token.Load(loo_Oauth.AccessTokenResponse)
if li_Success <> 1 then
Write-Debug "Could not parse the token response."
destroy loo_Oauth
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("refresh_token") <> 1) OR (loo_Token.StringOfEquals("refresh_token","",1) = 1) then
Write-Debug "No offline refresh token was issued. The existing cache was preserved."
destroy loo_Oauth
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
Write-Debug "The response did not contain an access token. The existing cache was preserved."
destroy loo_Oauth
destroy loo_Token
return
end if
loo_Obtained = create oleobject
li_rc = loo_Obtained.ConnectToNewObject("Chilkat.CkDateTime")
loo_Obtained.SetFromCurrentSystemTime()
loo_Token.UpdateString("obtained_at",loo_Obtained.GetAsTimestamp(0))
// The token response includes expires_in (seconds). Refresh before the access token expires.
// The file contains credentials: use a private, access-controlled directory.
li_Success = loo_Token.WriteFile("gmail-mail-token.json")
if li_Success <> 1 then
Write-Debug "Could not save the token file."
destroy loo_Oauth
destroy loo_Token
destroy loo_Obtained
return
end if
Write-Debug "Credentials saved in the private working directory."
destroy loo_Oauth
destroy loo_Token
destroy loo_Obtained