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

Gmail IMAP: 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 SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @iTmp1 int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

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

    DECLARE @oauth int
    EXEC @hr = sp_OACreate 'Chilkat.OAuth2', @oauth OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OASetProperty @oauth, 'TokenEndpoint', 'https://oauth2.googleapis.com/token'
    EXEC sp_OASetProperty @oauth, 'ClientId', 'YOUR_DESKTOP_CLIENT_ID'
    EXEC sp_OASetProperty @oauth, 'ClientSecret', 'YOUR_DESKTOP_CLIENT_SECRET'

    EXEC sp_OASetProperty @oauth, 'AuthorizationEndpoint', 'https://accounts.google.com/o/oauth2/v2/auth'
    EXEC sp_OASetProperty @oauth, 'LocalHost', '127.0.0.1'
    EXEC sp_OASetProperty @oauth, 'ListenPort', 55568
    EXEC sp_OASetProperty @oauth, 'ListenPortRangeEnd', 55578
    EXEC sp_OASetProperty @oauth, 'CodeChallenge', 1
    EXEC sp_OASetProperty @oauth, 'CodeChallengeMethod', 'S256'
    EXEC sp_OASetProperty @oauth, 'Scope', 'https://mail.google.com/'
    EXEC sp_OAMethod @oauth, 'AddAuthQueryParam', @success OUT, 'access_type', 'offline'
    IF @success <> 1
      BEGIN

        PRINT 'Could not configure offline access.'
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    --  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
    EXEC sp_OAMethod @oauth, 'AddAuthQueryParam', @success OUT, 'prompt', 'consent'
    IF @success <> 1
      BEGIN

        PRINT 'Could not configure consent.'
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    DECLARE @authUrl nvarchar(4000)
    EXEC sp_OAMethod @oauth, 'StartAuth', @authUrl OUT
    EXEC sp_OAGetProperty @oauth, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 <> 1
      BEGIN

        PRINT 'Could not start the loopback listener.'
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    EXEC sp_OAMethod @oauth, 'LaunchBrowser', @success OUT, @authUrl
    IF @success <> 1
      BEGIN
        EXEC sp_OAMethod @oauth, 'Cancel', @success OUT

        PRINT 'Could not open the system browser.'
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    DECLARE @waited int
    SELECT @waited = 0
    EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
    WHILE ((@iTmp0 < 3) and (@waited < 180000))
      BEGIN
        EXEC sp_OAMethod @oauth, 'SleepMs', NULL, 200
        SELECT @waited = @waited + 200
      END
    EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
    IF @iTmp0 < 3
      BEGIN
        EXEC sp_OAMethod @oauth, 'Cancel', @success OUT

        PRINT 'Authorization timed out.'
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
    IF @iTmp0 <> 3
      BEGIN

        EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
        PRINT 'Authorization did not complete. Flow state: ' + @iTmp0
        EXEC @hr = sp_OADestroy @oauth
        RETURN
      END
    DECLARE @token int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @token OUT

    EXEC sp_OAGetProperty @oauth, 'AccessTokenResponse', @sTmp0 OUT
    EXEC sp_OAMethod @token, 'Load', @success OUT, @sTmp0
    IF @success <> 1
      BEGIN

        PRINT 'Could not parse the token response.'
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @token
        RETURN
      END
    EXEC sp_OAMethod @token, 'JsonTypeOf', @iTmp0 OUT, 'refresh_token'
    EXEC sp_OAMethod @token, 'StringOfEquals', @iTmp1 OUT, 'refresh_token', '', 1
    IF (@iTmp0 <> 1) or (@iTmp1 = 1)
      BEGIN

        PRINT 'No offline refresh token was issued. The existing cache was preserved.'
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @token
        RETURN
      END
    EXEC sp_OAMethod @token, 'JsonTypeOf', @iTmp0 OUT, 'access_token'
    EXEC sp_OAMethod @token, 'StringOfEquals', @iTmp1 OUT, 'access_token', '', 1
    IF (@iTmp0 <> 1) or (@iTmp1 = 1)
      BEGIN

        PRINT 'The response did not contain an access token. The existing cache was preserved.'
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @token
        RETURN
      END
    DECLARE @obtained int
    EXEC @hr = sp_OACreate 'Chilkat.CkDateTime', @obtained OUT

    EXEC sp_OAMethod @obtained, 'SetFromCurrentSystemTime', @success OUT
    EXEC sp_OAMethod @obtained, 'GetAsTimestamp', @sTmp0 OUT, 0
    EXEC sp_OAMethod @token, 'UpdateString', @success OUT, 'obtained_at', @sTmp0
    --  The token response includes expires_in (seconds). Refresh before the access token expires.
    --  The file contains credentials: use a private, access-controlled directory.
    EXEC sp_OAMethod @token, 'WriteFile', @success OUT, 'gmail-mail-token.json'
    IF @success <> 1
      BEGIN

        PRINT 'Could not save the token file.'
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @token
        EXEC @hr = sp_OADestroy @obtained
        RETURN
      END

    PRINT 'Credentials saved in the private working directory.'

    EXEC @hr = sp_OADestroy @oauth
    EXEC @hr = sp_OADestroy @token
    EXEC @hr = sp_OADestroy @obtained


END
GO