I have successfully configurated Office365 environment to send and receive email following these docs:
https://blog.rebex.net/office365-imap-pop3-oauth-unattended
https://blog.rebex.net/office365-ews-oauth-unattended
Now I'm using Rebex library and C# code to check it.
The common part:
Common
string[] scopes = new[] {
"https://outlook.office365.com/.default", "openid", "email", "profile"
};
// get an instance of 'confidential client application' API
var cca = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecretValue)
.WithTenantId(tenantId)
.Build();
// acquire OAuth 2.0 access token from Microsoft 365
AuthenticationResult result = await cca.AcquireTokenForClient(scopes).ExecuteAsync();
string accessToken = result.AccessToken;
EWS version
using (var client = new Rebex.Net.Ews())
{
client.Connect("outlook.office365.com", SslMode.Implicit);
client.Settings.Impersonation = new EwsImpersonation() { SmtpAddress = emailAddress };
if (!client.IsAuthenticated)
client.Login(accessToken, EwsAuthentication.OAuth20);
var list = client.GetMessageList(EwsFolderId.Inbox);
client.SendMessage(mail);
client.Disconnect();
}
It works!
IMAP version
using (var client = new Imap())
{
client.Connect("outlook.office365.com", SslMode.Implicit);
string pattern2 = string.Format("user={0}{1}auth=Bearer {2}{1}{1}", emailAddress, '\x1', accessToken);
string token2 = Convert.ToBase64String(
Encoding.ASCII.GetBytes(pattern2));
client.Login(token2, ImapAuthentication.OAuth20);
}
It works!
SMTP version
using (var client = new Smtp())
{
// I tried also outlook.office365.com
client.Connect("smtp.office365.com", SslMode.Explicit);
string pattern2 = string.Format("user={0}{1}auth=Bearer {2}{1}{1}", emailAddress, '\x1', accessToken);
string token2 = Convert.ToBase64String(Encoding.ASCII.GetBytes(pattern2));
client.Login(emailAddress, token2, Rebex.Net.SmtpAuthentication.OAuth20);
client.Send(mail);
client.Disconnect();
}
Smtp login call returns Authentication unsuccessful (535)
The Rebex log:
[date] ERROR Smtp(1)[8] Info: Rebex.Net.SmtpException: Authentication unsuccessful [foo.foo.PROD.OUTLOOK.COM] (535). in Rebex.Net.Smtp.rozhm(String p0, String p1, SmtpAuthentication p2, GssApiProvider p3) in Rebex.Net.Smtp.hcpew(String p0, String p1, SmtpAuthentication p2)
Please see the Any issues? section in the mentioned articles. There is written:
Microsoft 365 does not support app-only authentication for SMTP yet. However, it will still be possible to enable username/password authentication for SMTP after October 1st 2022.
Please note that, when you are configuring your app for unattended access, you have to add some permissions from the Office 365 Exchange Online
group. There are permissions for EWS, IMAP, POP3, but there are currently no permissions for SMTP.
Hint: If you don't want to use real user's password for SMTP authentication, it is possible to generate an app password
and use it instead.