pjs11@R5124614 email_filter $ more ./imap_ad_clientcreds_test.pl #!/usr/bin/env perl use strict; use utf8; use URI::Escape; use MIME::Base64; use Mail::IMAPClient; use Azure::AD::ClientCredentialsV2; our $app_id = '**** MY APP ID ****'; our $secrets_id = '**** MY SECRET ID ****'; our $secrets_value = '**** MY SECRET VALUE ****'; our $tenant = '**** MY TENANT ID ****'; my $imapserver="outlook.office365.com"; my $username='tivolialertsdev@mayo.edu'; my $creds = Azure::AD::ClientCredentialsV2->new( resource_id => 'https://graph.windows.net/', client_id => $app_id, secret_id => $secrets_value, tenant_id => $tenant, scope => '.default', ); my $oauth_token = $creds->access_token; print "Received token: $oauth_token\n"; my $oauth_sign = encode_base64("user=". $username ."\x01auth=Bearer ". $oauth_token ."\x01\x01", ''); # detail: https://developers.google.com/google-apps/gmail/xoauth2_protocol print "Encoded: $oauth_sign\n"; my $imap = Mail::IMAPClient->new( Server => $imapserver, Port => 993, Ssl => 1, Uid => 1, IgnoreSizeErrors => 1, Debug => 1, ) or die('Can\'t connect to imap server.'); $imap->Showcredentials(1); # Massive debugging, please $imap->authenticate('XOAUTH2', sub { return $oauth_sign }) or die("Auth error: ". $imap->LastError);