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

Gmail IMAP: Refresh an OAuth2 Token

See more GMail SMTP/IMAP/POP Examples

Refresh a Gmail access token without opening a browser. Use the same OAuth client and the offline refresh token saved during initial authorization. A refreshed token can authenticate SMTP, IMAP, or POP3 for the authorized mailbox.

Google normally does not return another refresh token. The example retains the saved refresh token when omitted, accepts a replacement when provided, preserves the granted scope when omitted, and records the new access token's issue time and lifetime. A failed exchange leaves the old cache untouched. File writes are checked; production applications should use protected storage and serialize/atomically commit updates.

Access tokens normally last about an hour. Refresh ahead of expiry and reconnect long-lived protocol sessions when necessary. Refresh does not add scopes or restore a revoked grant. An invalid_grant response can require fresh user authorization; do not retry it indefinitely. External apps in Testing normally receive seven-day refresh tokens for this scope.

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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoToken
    Handle hoOauth
    Handle hoFresh
    Handle hoObtained
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Get ComLoadFile Of hoToken "gmail-mail-token.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not read gmail-mail-token.json from the private working directory."
        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 "Authorize the account for offline access first."
        Procedure_Return
    End

    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"
    Get ComStringOf Of hoToken "refresh_token" To sTemp1
    Set ComRefreshToken Of hoOauth To sTemp1
    Get ComRefreshAccessToken Of hoOauth To iSuccess
    If (iSuccess <> True) Begin
        Showln "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoFresh
    If (Not(IsComObjectCreated(hoFresh))) Begin
        Send CreateComObject of hoFresh
    End
    Get ComAccessTokenResponse Of hoOauth To sTemp1
    Get ComLoad Of hoFresh sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not parse the refresh response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoFresh "access_token" To iTemp1
    Get ComStringOfEquals Of hoFresh "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "The refresh response did not contain an access token."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoFresh "refresh_token" To iTemp1
    Get ComStringOfEquals Of hoFresh "refresh_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Get ComStringOf Of hoToken "refresh_token" To sTemp1
        Get ComUpdateString Of hoFresh "refresh_token" sTemp1 To iSuccess
    End

    Get ComHasMember Of hoFresh "scope" To bTemp1
    Get ComJsonTypeOf Of hoToken "scope" To iTemp1
    If ((bTemp1 <> True) And (iTemp1 = 1)) Begin
        Get ComStringOf Of hoToken "scope" To sTemp1
        Get ComUpdateString Of hoFresh "scope" sTemp1 To iSuccess
    End

    //  Google normally omits refresh_token on refresh. Keep the previous one in that case.
    //  Use the new expires_in, not the old response's expiration information.
    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 hoFresh "obtained_at" sTemp1 To iSuccess
    Get ComWriteFile Of hoFresh "gmail-mail-token.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the refreshed credentials."
        Procedure_Return
    End

    Showln "Refreshed the access token."


End_Procedure