Sample code for 30+ languages & platforms
PureBasic

IMAP Auto-Refresh Office365 Access Token

See more Office365 Examples

Demonstrates how to automatically recover from an expired access token when OAuth2 authentication fails in the IMAP protocol. If the server responds with "NO AUTHENTICATE failed.", then we refresh the access token and retry.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkImap.pb"
IncludeFile "CkOAuth2.pb"

Procedure ChilkatExample()

    success.i = 0

    ; An Office365 OAuth2 access token must first be obtained prior
    ; to running this code.

    ; Getting the OAuth2 access token for the 1st time requires the O365 account owner's 
    ; interactive authorizaition via a web browser.  Afterwards, the access token
    ; can be repeatedly refreshed automatically.

    ; See the following examples for getting and refreshing an OAuth2 access token

    ; Get Office365 SMTP/IMAP/POP3 OAuth2 Access Token
    ; Refresh Office365 SMTP/IMAP/POP3 OAuth2 Access Token

    ; First get our previously obtained OAuth2 access token.
    jsonToken.i = CkJsonObject::ckCreate()
    If jsonToken.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(jsonToken,"qa_data/tokens/office365.json")
    If success = 0
        Debug "Failed to open the office365 OAuth JSON file."
        CkJsonObject::ckDispose(jsonToken)
        ProcedureReturn
    EndIf

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

    CkImap::setCkSsl(imap, 1)
    CkImap::setCkPort(imap, 993)

    ; Connect to the Office365 IMAP server.
    success = CkImap::ckConnect(imap,"outlook.office365.com")
    If success <> 1
        Debug CkImap::ckLastErrorText(imap)
        CkJsonObject::ckDispose(jsonToken)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    ; Use OAuth2 authentication.
    CkImap::setCkAuthMethod(imap, "XOAUTH2")

    ; Login using our username (i.e. email address) and the access token for the password.
    success = CkImap::ckLogin(imap,"OFFICE365_EMAIL_ADDRESS",CkJsonObject::ckStringOf(jsonToken,"access_token"))
    If success <> 1
        loginLastErrorText.s = CkImap::ckLastErrorText(imap)

        ; If we're still connected to the mail server, then it means the server sent a non-success response,
        ; Such as:  NO AUTHENTICATE failed.
        If CkImap::ckIsConnected(imap) = 1

            ; Refresh the OAuth2 access token, and if successful, save the new (refreshed) access token and try authenticating again.
            oauth2.i = CkOAuth2::ckCreate()
            If oauth2.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            ; Use your actual Directory (tenant) ID instead of "112d7ed6-71bf-4eba-a866-738364321bfc"
            CkOAuth2::setCkTokenEndpoint(oauth2, "https://login.microsoftonline.com/112d7ed6-71bf-4eba-a866-738364321bfc/oauth2/v2.0/token")

            ; Replace these with your Azure App Registration's actual values.
            CkOAuth2::setCkClientId(oauth2, "CLIENT_ID")
            CkOAuth2::setCkClientSecret(oauth2, "CLIENT_SECRET")

            ; Get the "refresh_token"
            CkOAuth2::setCkRefreshToken(oauth2, CkJsonObject::ckStringOf(jsonToken,"refresh_token"))

            ; Send the HTTP POST to refresh the access token..
            success = CkOAuth2::ckRefreshAccessToken(oauth2)
            If success <> 1
                Debug CkOAuth2::ckLastErrorText(oauth2)
                CkJsonObject::ckDispose(jsonToken)
                CkImap::ckDispose(imap)
                CkOAuth2::ckDispose(oauth2)
                ProcedureReturn
            EndIf

            Debug "New access token: " + CkOAuth2::ckAccessToken(oauth2)
            Debug "New refresh token: " + CkOAuth2::ckRefreshToken(oauth2)

            ; Update the JSON with the new tokens.
            CkJsonObject::ckUpdateString(jsonToken,"access_token",CkOAuth2::ckAccessToken(oauth2))
            CkJsonObject::ckUpdateString(jsonToken,"refresh_token",CkOAuth2::ckRefreshToken(oauth2))

            ; Save the new JSON access token response to a file.
            sbJson.i = CkStringBuilder::ckCreate()
            If sbJson.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            CkJsonObject::setCkEmitCompact(jsonToken, 0)
            CkJsonObject::ckEmitSb(jsonToken,sbJson)
            CkStringBuilder::ckWriteFile(sbJson,"qa_data/tokens/office365.json","utf-8",0)

            Debug "New Access Token = " + CkOAuth2::ckAccessToken(oauth2)

            ; Retry the login.
            success = CkImap::ckLogin(imap,"OFFICE365_EMAIL_ADDRESS",CkJsonObject::ckStringOf(jsonToken,"access_token"))
            If success = 0
                Debug CkImap::ckLastErrorText(imap)
                CkJsonObject::ckDispose(jsonToken)
                CkImap::ckDispose(imap)
                CkOAuth2::ckDispose(oauth2)
                CkStringBuilder::ckDispose(sbJson)
                ProcedureReturn
            EndIf

        Else
            ; Show the last error text for the call to Login
            Debug loginLastErrorText
            CkJsonObject::ckDispose(jsonToken)
            CkImap::ckDispose(imap)
            CkOAuth2::ckDispose(oauth2)
            CkStringBuilder::ckDispose(sbJson)
            ProcedureReturn
        EndIf

    Else
        Debug "O365 OAuth authentication is successful."
    EndIf

    ; Do something...
    success = CkImap::ckSelectMailbox(imap,"Inbox")
    If success <> 1
        Debug CkImap::ckLastErrorText(imap)
        CkJsonObject::ckDispose(jsonToken)
        CkImap::ckDispose(imap)
        CkOAuth2::ckDispose(oauth2)
        CkStringBuilder::ckDispose(sbJson)
        ProcedureReturn
    EndIf

    ; Your application can continue to do other things in the IMAP session....

    ; When finished, logout and close the connection.
    success = CkImap::ckLogout(imap)
    success = CkImap::ckDisconnect(imap)

    Debug "Finished."


    CkJsonObject::ckDispose(jsonToken)
    CkImap::ckDispose(imap)
    CkOAuth2::ckDispose(oauth2)
    CkStringBuilder::ckDispose(sbJson)


    ProcedureReturn
EndProcedure