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

Gmail POP3: Obtain an OAuth2 Token

See more GMail SMTP/IMAP/POP Examples

This page is retained for existing links. It uses the same full-mail authorization as the shared Gmail protocol authorization example.

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 PureBasic Downloads

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkOAuth2.pb"
IncludeFile "CkDateTime.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    oauth.i = CkOAuth2::ckCreate()
    If oauth.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkOAuth2::setCkTokenEndpoint(oauth, "https://oauth2.googleapis.com/token")
    CkOAuth2::setCkClientId(oauth, "YOUR_DESKTOP_CLIENT_ID")
    CkOAuth2::setCkClientSecret(oauth, "YOUR_DESKTOP_CLIENT_SECRET")

    CkOAuth2::setCkAuthorizationEndpoint(oauth, "https://accounts.google.com/o/oauth2/v2/auth")
    CkOAuth2::setCkLocalHost(oauth, "127.0.0.1")
    CkOAuth2::setCkListenPort(oauth, 55568)
    CkOAuth2::setCkListenPortRangeEnd(oauth, 55578)
    CkOAuth2::setCkCodeChallenge(oauth, 1)
    CkOAuth2::setCkCodeChallengeMethod(oauth, "S256")
    CkOAuth2::setCkScope(oauth, "https://mail.google.com/")
    success = CkOAuth2::ckAddAuthQueryParam(oauth,"access_type","offline")
    If success <> 1
        Debug "Could not configure offline access."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    ;  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
    success = CkOAuth2::ckAddAuthQueryParam(oauth,"prompt","consent")
    If success <> 1
        Debug "Could not configure consent."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    authUrl.s = CkOAuth2::ckStartAuth(oauth)
    If CkOAuth2::ckLastMethodSuccess(oauth) <> 1
        Debug "Could not start the loopback listener."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    success = CkOAuth2::ckLaunchBrowser(oauth,authUrl)
    If success <> 1
        CkOAuth2::ckCancel(oauth)
        Debug "Could not open the system browser."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    waited.i = 0
    While ((CkOAuth2::ckAuthFlowState(oauth) < 3) AND (waited < 180000))
        CkOAuth2::ckSleepMs(oauth,200)
        waited = waited + 200
    Wend
    If CkOAuth2::ckAuthFlowState(oauth) < 3
        CkOAuth2::ckCancel(oauth)
        Debug "Authorization timed out."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    If CkOAuth2::ckAuthFlowState(oauth) <> 3
        Debug "Authorization did not complete. Flow state: " + Str(CkOAuth2::ckAuthFlowState(oauth))
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    token.i = CkJsonObject::ckCreate()
    If token.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(token,CkOAuth2::ckAccessTokenResponse(oauth))
    If success <> 1
        Debug "Could not parse the token response."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"refresh_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"refresh_token","",1) = 1)
        Debug "No offline refresh token was issued. The existing cache was preserved."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"access_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"access_token","",1) = 1)
        Debug "The response did not contain an access token. The existing cache was preserved."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    obtained.i = CkDateTime::ckCreate()
    If obtained.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkDateTime::ckSetFromCurrentSystemTime(obtained)
    CkJsonObject::ckUpdateString(token,"obtained_at",CkDateTime::ckGetAsTimestamp(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.
    success = CkJsonObject::ckWriteFile(token,"gmail-mail-token.json")
    If success <> 1
        Debug "Could not save the token file."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        CkDateTime::ckDispose(obtained)
        ProcedureReturn
    EndIf

    Debug "Credentials saved in the private working directory."


    CkOAuth2::ckDispose(oauth)
    CkJsonObject::ckDispose(token)
    CkDateTime::ckDispose(obtained)


    ProcedureReturn
EndProcedure