Using Oauth2 to send email via Office365 C#

Viewed 10565

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.

2 Answers

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);
}

You can use the EWS managed api by creating an OAuthCredentials object using the OAuth token and then setting the credentials and endpoint on an ExchangeService object. You can then use the ExchangeService object to create and send the email.

var credentials = new OAuthCredentials(token);
var ews = new ExchangeService();
ews.Credentials = credentials;
ews.Url = endpointUrl;

var email = new EmailMessage(ews);
...

email.Send();

https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-managed-api-reference-for-exchange

The go forward method would be Microsoft Graph, but I'm not as familiar with it. https://docs.microsoft.com/en-us/graph/api/resources/mail-api-overview?view=graph-rest-1.0

Related