+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.

by

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.Connect("outlook.office365.com");
    smtp.StartTLS();

    smtp.LoginOAUTH2(userName, accessToken)

    smtp.SendMessage(email);                     
    smtp.Close();   
}              
by (297k 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 = {
    "offline_access",
    "email",
    "Mail.Send",
    "https://graph.microsoft.com/IMAP.AccessAsUser.All",
    "https://graph.microsoft.com/SMTP.Send" };

app = PublicClientApplicationBuilder.Create(clientId)                              
    .WithAuthority(
        AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
    .WithDefaultRedirectUri()
    .Build();

var result = await app.AcquireTokenInteractive(msScopes)
    .ExecuteAsync();

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

Those scopes don't look correct.

Those are correct ones:

var scopes = new string[] 
{
    "offline_access",
    "email",
    "https://outlook.office.com/IMAP.AccessAsUser.All",
    "https://outlook.office.com/POP.AccessAsUser.All",
    "https://outlook.office.com/SMTP.Send",
};

It looks like you are implementing desktop app flow:
https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp

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:
https://www.limilabs.com/blog/office365-enable-imap-pop3-smtp

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.

...