I'm trying to send email in c# using Oauth2 with an office 365 account.
Currently I am able to get the token but not sure how I'm able to use that token and send the email.
System.Net.Mail does not support OAuth or OAuth2.
I've seen Mailkit but the samples are all for google mail and didn't see one for office 365 so I'm not really sure where to start.
The documentation for OAuth2 authentication using MailKit with Office365 can be found here: https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md
var options = new PublicClientApplicationOptions {
ClientId = "Application (client) ID",
TenantId = "Directory (tenant) ID",
RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
};
var publicClientApplication = PublicClientApplicationBuilder
.CreateWithApplicationOptions (options)
.Build ();
var scopes = new string[] {
"email",
"offline_access",
"https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
//"https://outlook.office.com/POP.AccessAsUser.All", // Only needed for POP
//"https://outlook.office.com/SMTP.Send", // Only needed for SMTP
};
var authToken = await publicClientApplication.AcquireTokenInteractive (scopes).ExecuteAsync ();
var oauth2 = new SaslMechanismOAuth2 (authToken.Account.Username, authToken.AccessToken);
using (var client = new ImapClient ()) {
await client.ConnectAsync ("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
await client.AuthenticateAsync (oauth2);
await client.DisconnectAsync (true);
}