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 DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoOauth
String sAuthUrl
Integer iWaited
Handle hoToken
Handle hoObtained
String sTemp1
Integer iTemp1
Boolean bTemp1
Move False To iSuccess
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Get Create (RefClass(cComChilkatOAuth2)) To hoOauth
If (Not(IsComObjectCreated(hoOauth))) Begin
Send CreateComObject of hoOauth
End
Set ComTokenEndpoint Of hoOauth To "https://oauth2.googleapis.com/token"
Set ComClientId Of hoOauth To "YOUR_DESKTOP_CLIENT_ID"
Set ComClientSecret Of hoOauth To "YOUR_DESKTOP_CLIENT_SECRET"
Set ComAuthorizationEndpoint Of hoOauth To "https://accounts.google.com/o/oauth2/v2/auth"
Set ComLocalHost Of hoOauth To "127.0.0.1"
Set ComListenPort Of hoOauth To 55568
Set ComListenPortRangeEnd Of hoOauth To 55578
Set ComCodeChallenge Of hoOauth To True
Set ComCodeChallengeMethod Of hoOauth To "S256"
Set ComScope Of hoOauth To "https://mail.google.com/"
Get ComAddAuthQueryParam Of hoOauth "access_type" "offline" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not configure offline access."
Procedure_Return
End
// This is the interactive setup step. Subsequent refreshes use the saved refresh token.
Get ComAddAuthQueryParam Of hoOauth "prompt" "consent" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not configure consent."
Procedure_Return
End
Get ComStartAuth Of hoOauth To sAuthUrl
Get ComLastMethodSuccess Of hoOauth To bTemp1
If (bTemp1 <> True) Begin
Showln "Could not start the loopback listener."
Procedure_Return
End
Get ComLaunchBrowser Of hoOauth sAuthUrl To iSuccess
If (iSuccess <> True) Begin
Get ComCancel Of hoOauth To iSuccess
Showln "Could not open the system browser."
Procedure_Return
End
Move 0 To iWaited
While (((ComAuthFlowState(hoOauth)) < 3) And (iWaited < 180000))
Send ComSleepMs To hoOauth 200
Move (iWaited + 200) To iWaited
Loop
Get ComAuthFlowState Of hoOauth To iTemp1
If (iTemp1 < 3) Begin
Get ComCancel Of hoOauth To iSuccess
Showln "Authorization timed out."
Procedure_Return
End
Get ComAuthFlowState Of hoOauth To iTemp1
If (iTemp1 <> 3) Begin
Get ComAuthFlowState Of hoOauth To iTemp1
Showln "Authorization did not complete. Flow state: " iTemp1
Procedure_Return
End
Get Create (RefClass(cComChilkatJsonObject)) To hoToken
If (Not(IsComObjectCreated(hoToken))) Begin
Send CreateComObject of hoToken
End
Get ComAccessTokenResponse Of hoOauth To sTemp1
Get ComLoad Of hoToken sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not parse the token response."
Procedure_Return
End
Get ComJsonTypeOf Of hoToken "refresh_token" To iTemp1
Get ComStringOfEquals Of hoToken "refresh_token" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "No offline refresh token was issued. The existing cache was preserved."
Procedure_Return
End
Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "The response did not contain an access token. The existing cache was preserved."
Procedure_Return
End
Get Create (RefClass(cComCkDateTime)) To hoObtained
If (Not(IsComObjectCreated(hoObtained))) Begin
Send CreateComObject of hoObtained
End
Get ComSetFromCurrentSystemTime Of hoObtained To iSuccess
Get ComGetAsTimestamp Of hoObtained False To sTemp1
Get ComUpdateString Of hoToken "obtained_at" sTemp1 To iSuccess
// The token response includes expires_in (seconds). Refresh before the access token expires.
// The file contains credentials: use a private, access-controlled directory.
Get ComWriteFile Of hoToken "gmail-mail-token.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not save the token file."
Procedure_Return
End
Showln "Credentials saved in the private working directory."
End_Procedure