Sample code for 30+ languages & platforms
Zig

Office365 POP3 Login with OAuth2 Authentication

See more Office365 Examples

Demonstrates how to authenticate using OAuth2 using the POP3 protocol with outlook.office365.com.

Note: This example requires Chilkat v9.5.0.83 or greater.

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 {
        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. [QwBIADIAUABSADEAOABD...YwBvAG0A]
    // > AUTH XOAUTH2
    // < +
    // > <base64 string in XOAUTH2 format>
    // < +OK User successfully authenticated.
    // > STAT
    // < +OK 3 375302

    // 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", .{});
}