Sample code for 30+ languages & platforms
PowerBuilder

POP3 Auto-Refresh Office365 Access Token

See more Office365 Examples

Demonstrates how to automatically recover from an expired OAuth2 access token when OAuth2 authentication fails in the POP3 protocol. If the server responds with "-ERR Authentication failure: unknown user name or bad password.", then we refresh the access token and retry.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Mailman
oleobject loo_JsonToken
oleobject loo_Oauth2
oleobject loo_SbJson
integer li_NumEmails

li_Success = 0

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

loo_Mailman = create oleobject
li_rc = loo_Mailman.ConnectToNewObject("Chilkat.MailMan")
if li_rc < 0 then
    destroy loo_Mailman
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_Mailman.MailHost = "outlook.office365.com"
loo_Mailman.MailPort = 995
loo_Mailman.PopSsl = 1

// Use your O365 email address here.
loo_Mailman.PopUsername = "OFFICE365_EMAIL_ADDRESS"

// When using OAuth2 authentication, leave the password empty.
loo_Mailman.PopPassword = ""

// Load our previously obtained OAuth2 access token.
loo_JsonToken = create oleobject
li_rc = loo_JsonToken.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_JsonToken.LoadFile("qa_data/tokens/office365.json")
if li_Success = 0 then
    Write-Debug loo_JsonToken.LastErrorText
    destroy loo_Mailman
    destroy loo_JsonToken
    return
end if

loo_Mailman.OAuth2AccessToken = loo_JsonToken.StringOf("access_token")

// Make the TLS connection to the outlook.office365.com POP3 server.
li_Success = loo_Mailman.Pop3Connect()
if li_Success <> 1 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Mailman
    destroy loo_JsonToken
    return
end if

// Authenticate using XOAUTH2
li_Success = loo_Mailman.Pop3Authenticate()
if li_Success <> 1 then
    // If we're still connected to the mail server, then it means the server sent a non-success response,
    // Such as:  -ERR Authentication failure: unknown user name or bad password.
    if loo_Mailman.IsPop3Connected = 1 then

        // Refresh the OAuth2 access token, and if successful, save the new (refreshed) access token and try authenticating again.
        loo_Oauth2 = create oleobject
        li_rc = loo_Oauth2.ConnectToNewObject("Chilkat.OAuth2")

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

        // Replace these with your Azure App Registration's actual values.
        loo_Oauth2.ClientId = "CLIENT_ID"
        loo_Oauth2.ClientSecret = "CLIENT_SECRET"

        // Get the "refresh_token"
        loo_Oauth2.RefreshToken = loo_JsonToken.StringOf("refresh_token")

        // Send the HTTP POST to refresh the access token..
        li_Success = loo_Oauth2.RefreshAccessToken()
        if li_Success <> 1 then
            Write-Debug loo_Oauth2.LastErrorText
            destroy loo_Mailman
            destroy loo_JsonToken
            destroy loo_Oauth2
            return
        end if

        Write-Debug "New access token: " + loo_Oauth2.AccessToken
        Write-Debug "New refresh token: " + loo_Oauth2.RefreshToken

        // Update the JSON with the new tokens.
        loo_JsonToken.UpdateString("access_token",loo_Oauth2.AccessToken)
        loo_JsonToken.UpdateString("refresh_token",loo_Oauth2.RefreshToken)

        // Save the new JSON access token response to a file.
        loo_SbJson = create oleobject
        li_rc = loo_SbJson.ConnectToNewObject("Chilkat.StringBuilder")

        loo_JsonToken.EmitCompact = 0
        loo_JsonToken.EmitSb(loo_SbJson)
        loo_SbJson.WriteFile("qa_data/tokens/office365.json","utf-8",0)

        Write-Debug "New Access Token = " + loo_Oauth2.AccessToken

        // Update the mailman with the new access token.
        loo_Mailman.OAuth2AccessToken = loo_Oauth2.AccessToken

        // Retry the authentication.
        li_Success = loo_Mailman.Pop3Authenticate()
        if li_Success = 0 then
            Write-Debug loo_Mailman.LastErrorText
            destroy loo_Mailman
            destroy loo_JsonToken
            destroy loo_Oauth2
            destroy loo_SbJson
            return
        end if

    else
        Write-Debug loo_Mailman.LastErrorText
        destroy loo_Mailman
        destroy loo_JsonToken
        destroy loo_Oauth2
        destroy loo_SbJson
        return
    end if

end if

// Find out how many emails are on the server..
li_NumEmails = loo_Mailman.CheckMail()
if li_NumEmails < 0 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Mailman
    destroy loo_JsonToken
    destroy loo_Oauth2
    destroy loo_SbJson
    return
end if

// Examine the POP3 session log:
Write-Debug loo_Mailman.Pop3SessionLog

// The POP3 session log will look something like this:

// **** Connected to outlook.office365.com:995
// < +OK The Microsoft Exchange POP3 service is ready. [QwBIADIAUABSADEANgBDAEEAMAAwADEAMgAuAG4AYQBtAHAAcgBkADEANgAuAHAAcgBvAGQALgBvAHUAdABsAG8AbwBrAC4AYwBvAG0A]
// > AUTH XOAUTH2
// < + 
// > <base64 string in XOAUTH2 format>
// < -ERR Authentication failure: unknown user name or bad password.
// > AUTH XOAUTH2
// < + 
// > <base64 string in XOAUTH2 format>
// < +OK User successfully authenticated.
// > STAT
// < +OK 248 46637086

// End the POP3 session and close the connection to the GMail server.
li_Success = loo_Mailman.Pop3EndSession()
if li_Success <> 1 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Mailman
    destroy loo_JsonToken
    destroy loo_Oauth2
    destroy loo_SbJson
    return
end if

Write-Debug "Finished."


destroy loo_Mailman
destroy loo_JsonToken
destroy loo_Oauth2
destroy loo_SbJson