Sample code for 30+ languages & platforms
Zig

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

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

    mailman.setMailHost("outlook.office365.com");
    mailman.setMailPort(995);
    mailman.setPopSsl(true);

    // Use your O365 email address here.
    mailman.setPopUsername("OFFICE365_EMAIL_ADDRESS");

    // When using OAuth2 authentication, leave the password empty.
    mailman.setPopPassword("");

    // Load our previously obtained OAuth2 access token.
    const json_token = try chilkat.JsonObject.init();
    defer json_token.deinit();
    json_token.loadFile("qa_data/tokens/office365.json") catch {
        std.debug.print("{s}\n", .{try json_token.getLastErrorText(alloc)});
        return;
    };

    mailman.setOAuth2AccessToken(try json_token.stringOf(alloc, "access_token"));

    // Make the TLS connection to the outlook.office365.com POP3 server.
    mailman.pop3Connect() catch {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    };

    // Authenticate using XOAUTH2
    mailman.pop3Authenticate() catch {
        // 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 (mailman.getIsPop3Connected()) {
            // Refresh the OAuth2 access token, and if successful, save the new (refreshed) access token and try authenticating again.
            const oauth2 = try chilkat.OAuth2.init();
            defer oauth2.deinit();

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

            // Replace these with your Azure App Registration's 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("New Access Token = {s}\n", .{try oauth2.getAccessToken(alloc)});

            // Update the mailman with the new access token.
            mailman.setOAuth2AccessToken(try oauth2.getAccessToken(alloc));

            // Retry the authentication.
            mailman.pop3Authenticate() catch {
                std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
                return;
            };
        } else {
            std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
            return;
        }
    };

    // Find out how many emails are on the server..
    const num_emails = mailman.checkMail();
    if (num_emails < 0) {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    }

    // Examine the POP3 session log:
    std.debug.print("{s}\n", .{try mailman.getPop3SessionLog(alloc)});

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

    std.debug.print("Finished.\n", .{});
}