Sample code for 30+ languages & platforms
PowerBuilder

Auto-Refresh O365 Access Token when Sending Email

See more Office365 Examples

Demonstrates how to automatically recover from an expired access token when sending email from smtp.office365.com using OAuth2 authentication. If the server responds with an error indicating that the access token is expired, then we refresh the access token and retry.

Chilkat PowerBuilder Downloads

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

li_Success = 0

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

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

// First get our previously obtained OAuth2 access token.
loo_JsonToken = create oleobject
li_rc = loo_JsonToken.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_JsonToken
    MessageBox("Error","Connecting to COM object failed")
    return
end if
li_Success = loo_JsonToken.LoadFile("qa_data/tokens/office365.json")

loo_Mailman = create oleobject
li_rc = loo_Mailman.ConnectToNewObject("Chilkat.MailMan")

loo_Mailman.SmtpHost = "smtp.office365.com"
loo_Mailman.SmtpPort = 587
loo_Mailman.StartTLS = 1

// Use your Office365 email address for the SmtpUsername.
loo_Mailman.SmtpUsername = "OFFICE365_EMAIL_ADDRESS"
loo_Mailman.OAuth2AccessToken = loo_JsonToken.StringOf("access_token")

// Create a new email object
loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")

loo_Email.Subject = "This is a test"
loo_Email.Body = "This is a test"
loo_Email.From = "MY_NAME <OFFICE365_EMAIL_ADDRESS>"
li_Success = loo_Email.AddTo("John Doe","somebody@example.com")

// Call SendEmail to connect to the SMTP server and send.
// The connection (i.e. session) to the SMTP server remains
// open so that subsequent SendEmail calls may use the
// same connection.  
li_Success = loo_Mailman.SendEmail(loo_Email)
if li_Success = 1 then
    Write-Debug "Mail Sent!"
    destroy loo_JsonToken
    destroy loo_Mailman
    destroy loo_Email
    return
end if

// If we fall through to here, it means something failed.
// If we failed because of an invalid or expired access token, we should get this SMTP status code and error message:
//    response: 535 5.7.3 Authentication unsuccessful [CH2PR19CA0023.namprd19.prod.outlook.com]
//    status code: 535
if loo_Mailman.LastSmtpStatus <> 535 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_JsonToken
    destroy loo_Mailman
    destroy loo_Email
    return
end if

// If we get here, it means the SMTP status code equaled 535, which is an authentication failure.
// Let's refresh the access token, and then retry..

loo_Oauth2 = create oleobject
li_rc = loo_Oauth2.ConnectToNewObject("Chilkat.OAuth2")

// Update to use your token endpoint.
// In the Azure Portal, in "App registrations", go to "Endpoints" (located to the right of the "+ New registration" link.)
//    Find your endpoint for the "OAuth 2.0 token endpoint (v2)"
//    See Office365 OAuth2 Endpoints

loo_Oauth2.TokenEndpoint = "https://login.microsoftonline.com/xxxxxxxxxx-71bf-4ebe-a866-738364321bf2/oauth2/v2.0/token"

// Replace these with 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_JsonToken
    destroy loo_Mailman
    destroy loo_Email
    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 "OAuth2 authorization granted!"
Write-Debug "New Access Token = " + loo_Oauth2.AccessToken

// -------------------------------------------------
// Retry the SMTP send using the refreshed access token.

Write-Debug "Retrying the send using the refreshed access token."

loo_Mailman.OAuth2AccessToken = loo_Oauth2.AccessToken

li_Success = loo_Mailman.SendEmail(loo_Email)
if li_Success = 0 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_JsonToken
    destroy loo_Mailman
    destroy loo_Email
    destroy loo_Oauth2
    destroy loo_SbJson
    return
end if

li_Success = loo_Mailman.CloseSmtpConnection()
if li_Success <> 1 then
    Write-Debug "Connection to SMTP server not closed cleanly."
end if

Write-Debug "Email sent!"


destroy loo_JsonToken
destroy loo_Mailman
destroy loo_Email
destroy loo_Oauth2
destroy loo_SbJson