+1 vote

I have tryed and searched a way to send mail with mail.dll and OAuth2.0 authentication for office365, but i can't find one.


1 Answer

0 votes

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

For all other flows (web, desktop, password grant, device) SMTP is supported:

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("from@example.com"));
builder.To.Add(new MailBox("to@example.com"));
builder.Subject = "Subject";
builder.Html = @"Html with an image: <img src=""cid:lena"" />";

var visual = builder.AddVisual(@"c:\lena.jpeg");
visual.ContentId = "lena";

var attachment = builder.AddAttachment(@"c:\tmp.doc");
attachment.SetFileName("document.doc", guessContentType: true);

IMail email = builder.Create();

using(Smtp smtp = new Smtp())

    smtp.LoginOAUTH2(userName, accessToken)

by (298k points)

I have tryed this solution, but on smtp.LoginOAUTH2(userName, accessToken) i receve this error:

Limilabs.Client.SMTP.SmtpResponseException: 'Authentication unsuccessful [MR1P264CA0044.FRAP264.PROD.OUTLOOK.COM]'

The token used is generated from:

IPublicClientApplication app;

string clientId = "client-id";
string[] msScopes = {
    "https://graph.microsoft.com/SMTP.Send" };

app = PublicClientApplicationBuilder.Create(clientId)                              

var result = await app.AcquireTokenInteractive(msScopes)

userName = result.Account.Username;
accessToken = result.AccessToken;

Those scopes don't look correct.

Those are correct ones:

var scopes = new string[] 

It looks like you are implementing desktop app flow:

I strongly suggest going through the article very carefully.

Every single step is needed and must be replicated for OAuth 2.0 to work.

Make sure SMTP is enabled for your organization and mailbox:

Be careful adding app permissions, remember to 'Grant consent', make sure you are using correct tenant id and app id in your code.

Thanks for the help, whith "https://outlook.office.com/SMTP.Send" it works fine.