Sample code for 30+ languages & platforms
Tcl

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

Tcl

load ./chilkat.dll

set 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.
set jsonToken [new_CkJsonObject]

set success [CkJsonObject_LoadFile $jsonToken "qa_data/tokens/office365.json"]

set mailman [new_CkMailMan]

CkMailMan_put_SmtpHost $mailman "smtp.office365.com"
CkMailMan_put_SmtpPort $mailman 587
CkMailMan_put_StartTLS $mailman 1

# Use your Office365 email address for the SmtpUsername.
CkMailMan_put_SmtpUsername $mailman "OFFICE365_EMAIL_ADDRESS"
CkMailMan_put_OAuth2AccessToken $mailman [CkJsonObject_stringOf $jsonToken "access_token"]

# Create a new email object
set email [new_CkEmail]

CkEmail_put_Subject $email "This is a test"
CkEmail_put_Body $email "This is a test"
CkEmail_put_From $email "MY_NAME <OFFICE365_EMAIL_ADDRESS>"
set success [CkEmail_AddTo $email "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.  
set success [CkMailMan_SendEmail $mailman $email]
if {$success == 1} then {
    puts "Mail Sent!"
    delete_CkJsonObject $jsonToken
    delete_CkMailMan $mailman
    delete_CkEmail $email
    exit
}

# 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 {[CkMailMan_get_LastSmtpStatus $mailman] != 535} then {
    puts [CkMailMan_lastErrorText $mailman]
    delete_CkJsonObject $jsonToken
    delete_CkMailMan $mailman
    delete_CkEmail $email
    exit
}

# 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..

set oauth2 [new_CkOAuth2]

# 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

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

# Replace these with actual values.
CkOAuth2_put_ClientId $oauth2 "CLIENT_ID"
CkOAuth2_put_ClientSecret $oauth2 "CLIENT_SECRET"

# Get the "refresh_token"
CkOAuth2_put_RefreshToken $oauth2 [CkJsonObject_stringOf $jsonToken "refresh_token"]

# Send the HTTP POST to refresh the access token..
set success [CkOAuth2_RefreshAccessToken $oauth2]
if {$success != 1} then {
    puts [CkOAuth2_lastErrorText $oauth2]
    delete_CkJsonObject $jsonToken
    delete_CkMailMan $mailman
    delete_CkEmail $email
    delete_CkOAuth2 $oauth2
    exit
}

puts "New access token: [CkOAuth2_accessToken $oauth2]"
puts "New refresh token: [CkOAuth2_refreshToken $oauth2]"

# Update the JSON with the new tokens.
CkJsonObject_UpdateString $jsonToken "access_token" [CkOAuth2_accessToken $oauth2]
CkJsonObject_UpdateString $jsonToken "refresh_token" [CkOAuth2_refreshToken $oauth2]

# Save the new JSON access token response to a file.
set sbJson [new_CkStringBuilder]

CkJsonObject_put_EmitCompact $jsonToken 0
CkJsonObject_EmitSb $jsonToken $sbJson
CkStringBuilder_WriteFile $sbJson "qa_data/tokens/office365.json" "utf-8" 0

puts "OAuth2 authorization granted!"
puts "New Access Token = [CkOAuth2_accessToken $oauth2]"

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

puts "Retrying the send using the refreshed access token."

CkMailMan_put_OAuth2AccessToken $mailman [CkOAuth2_accessToken $oauth2]

set success [CkMailMan_SendEmail $mailman $email]
if {$success == 0} then {
    puts [CkMailMan_lastErrorText $mailman]
    delete_CkJsonObject $jsonToken
    delete_CkMailMan $mailman
    delete_CkEmail $email
    delete_CkOAuth2 $oauth2
    delete_CkStringBuilder $sbJson
    exit
}

set success [CkMailMan_CloseSmtpConnection $mailman]
if {$success != 1} then {
    puts "Connection to SMTP server not closed cleanly."
}

puts "Email sent!"

delete_CkJsonObject $jsonToken
delete_CkMailMan $mailman
delete_CkEmail $email
delete_CkOAuth2 $oauth2
delete_CkStringBuilder $sbJson