+2 votes

We would like to use mail.dll to send email via SMTP and oauth2 modern auth.

We have added and granted a Mail.Send permission from office exchange online API

I searched for a sample code but could not find one.

This is the code that we have

var app = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .Build();

string[] scopes = new string[] {
"https://outlook.office365.com/.default"
};

var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

string accessToken = result.AccessToken;

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox(userEmail, "test"));
builder.To.Add(new MailBox("test@test.com", "User"));
builder.Subject = "This is HTML test";

builder.Html =                            // Set HTML body
    "This is <strong>HTML</strong> message, " +
    "with embeddedimage:<br />" +
    "<img src = 'cid:image1' />.";

IMail email = builder.Create();
using (Smtp smtp = new Smtp())
{
    smtp.Connect("smtp.office365.com", 587);
    smtp.StartTLS();
    smtp.LoginOAUTH2(userEmail, accessToken);
    smtp.SendMessage(email);
    smtp.Close();
}

Getting the following error

{"Authentication unsuccessful [BLAPR03CA0077.namprd03.prod.outlook.com]"}
by (600 points)

1 Answer

+1 vote
 
Best answer

Currently Microsoft doesn't support client credential flow + SMTP.

For this flow POP3 and IMAP permissions are available: POP.AccessAsApp for POP3 client access and IMAP.AccessAsApp for IMAP client access

All other flows (web, desktop, password grant, device) allow for SMTP as well.

I also believe they don't plan to disable basic auth for SMTP:

https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/deprecation-of-basic-authentication-exchange-online

"SMTP AUTH will still be available when Basic authentication is permanently disabled on October 1, 2022."

"We're also disabling SMTP AUTH in all tenants in which it's not being used."

Here's how to enable SMTP AUTH:
https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission

by (301k points)
selected by
How to send email using OAuth2
...