Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.0.0+

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.

Google documentation

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

set oauth [new_CkOAuth2]

CkOAuth2_put_TokenEndpoint $oauth "https://oauth2.googleapis.com/token"
CkOAuth2_put_ClientId $oauth "YOUR_DESKTOP_CLIENT_ID"
CkOAuth2_put_ClientSecret $oauth "YOUR_DESKTOP_CLIENT_SECRET"

CkOAuth2_put_AuthorizationEndpoint $oauth "https://accounts.google.com/o/oauth2/v2/auth"
CkOAuth2_put_LocalHost $oauth "127.0.0.1"
CkOAuth2_put_ListenPort $oauth 55568
CkOAuth2_put_ListenPortRangeEnd $oauth 55578
CkOAuth2_put_CodeChallenge $oauth 1
CkOAuth2_put_CodeChallengeMethod $oauth "S256"
CkOAuth2_put_Scope $oauth "https://mail.google.com/"
set success [CkOAuth2_AddAuthQueryParam $oauth "access_type" "offline"]
if {$success != 1} then {
    puts "Could not configure offline access."
    delete_CkOAuth2 $oauth
    exit
}

#  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
set success [CkOAuth2_AddAuthQueryParam $oauth "prompt" "consent"]
if {$success != 1} then {
    puts "Could not configure consent."
    delete_CkOAuth2 $oauth
    exit
}

set authUrl [CkOAuth2_startAuth $oauth]
if {[CkOAuth2_get_LastMethodSuccess $oauth] != 1} then {
    puts "Could not start the loopback listener."
    delete_CkOAuth2 $oauth
    exit
}

set success [CkOAuth2_LaunchBrowser $oauth $authUrl]
if {$success != 1} then {
    CkOAuth2_Cancel $oauth
    puts "Could not open the system browser."
    delete_CkOAuth2 $oauth
    exit
}

set waited 0
while {expr [[CkOAuth2_get_AuthFlowState $oauth] < 3]  &&  [$waited < 180000]} {
    CkOAuth2_SleepMs $oauth 200
    set waited [expr $waited + 200]
}
if {[CkOAuth2_get_AuthFlowState $oauth] < 3} then {
    CkOAuth2_Cancel $oauth
    puts "Authorization timed out."
    delete_CkOAuth2 $oauth
    exit
}

if {[CkOAuth2_get_AuthFlowState $oauth] != 3} then {
    puts "Authorization did not complete. Flow state: [CkOAuth2_get_AuthFlowState $oauth]"
    delete_CkOAuth2 $oauth
    exit
}

set token [new_CkJsonObject]

set success [CkJsonObject_Load $token [CkOAuth2_accessTokenResponse $oauth]]
if {$success != 1} then {
    puts "Could not parse the token response."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "refresh_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "refresh_token" "" 1] == 1]} then {
    puts "No offline refresh token was issued. The existing cache was preserved."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "access_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "access_token" "" 1] == 1]} then {
    puts "The response did not contain an access token. The existing cache was preserved."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

set obtained [new_CkDateTime]

CkDateTime_SetFromCurrentSystemTime $obtained
CkJsonObject_UpdateString $token "obtained_at" [CkDateTime_getAsTimestamp $obtained 0]
#  The token response includes expires_in (seconds). Refresh before the access token expires.
#  The file contains credentials: use a private, access-controlled directory.
set success [CkJsonObject_WriteFile $token "gmail-mail-token.json"]
if {$success != 1} then {
    puts "Could not save the token file."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    delete_CkDateTime $obtained
    exit
}

puts "Credentials saved in the private working directory."

delete_CkOAuth2 $oauth
delete_CkJsonObject $token
delete_CkDateTime $obtained