Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // 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.
    const json_token = try chilkat.JsonObject.init();
    defer json_token.deinit();
    try json_token.loadFile("qa_data/tokens/office365.json");

    const mailman = try chilkat.MailMan.init();
    defer mailman.deinit();

    mailman.setSmtpHost("smtp.office365.com");
    mailman.setSmtpPort(587);
    mailman.setStartTLS(true);

    // Use your Office365 email address for the SmtpUsername.
    mailman.setSmtpUsername("OFFICE365_EMAIL_ADDRESS");
    mailman.setOAuth2AccessToken(try json_token.stringOf(alloc, "access_token"));

    // Create a new email object
    const email = try chilkat.Email.init();
    defer email.deinit();

    email.setSubject("This is a test");
    email.setBody("This is a test");
    email.setFrom("MY_NAME <OFFICE365_EMAIL_ADDRESS>");
    try 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.
    if (mailman.sendEmail(email)) {
        std.debug.print("Mail Sent!\n", .{});
        return;
    } else |_| {}

    // 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 (mailman.getLastSmtpStatus() != 535) {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    }

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

    const oauth2 = try chilkat.OAuth2.init();
    defer oauth2.deinit();

    // 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

    oauth2.setTokenEndpoint("https://login.microsoftonline.com/xxxxxxxxxx-71bf-4ebe-a866-738364321bf2/oauth2/v2.0/token");

    // Replace these with actual values.
    oauth2.setClientId("CLIENT_ID");
    oauth2.setClientSecret("CLIENT_SECRET");

    // Get the "refresh_token"
    oauth2.setRefreshToken(try json_token.stringOf(alloc, "refresh_token"));

    // Send the HTTP POST to refresh the access token..
    oauth2.refreshAccessToken() catch {
        std.debug.print("{s}\n", .{try oauth2.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("New access token: {s}\n", .{try oauth2.getAccessToken(alloc)});
    std.debug.print("New refresh token: {s}\n", .{try oauth2.getRefreshToken(alloc)});

    // Update the JSON with the new tokens.
    json_token.updateString("access_token", try oauth2.getAccessToken(alloc)) catch {};
    json_token.updateString("refresh_token", try oauth2.getRefreshToken(alloc)) catch {};

    // Save the new JSON access token response to a file.
    const sb_json = try chilkat.StringBuilder.init();
    defer sb_json.deinit();
    json_token.setEmitCompact(false);
    json_token.emitSb(sb_json) catch {};
    sb_json.writeFile("qa_data/tokens/office365.json", "utf-8", false) catch {};

    std.debug.print("OAuth2 authorization granted!\n", .{});
    std.debug.print("New Access Token = {s}\n", .{try oauth2.getAccessToken(alloc)});

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

    std.debug.print("Retrying the send using the refreshed access token.\n", .{});

    mailman.setOAuth2AccessToken(try oauth2.getAccessToken(alloc));

    mailman.sendEmail(email) catch {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    };

    mailman.closeSmtpConnection() catch {
        std.debug.print("Connection to SMTP server not closed cleanly.\n", .{});
    };

    std.debug.print("Email sent!\n", .{});
}