Using Microsoft/Office 365 OAUTH + EWS and Ms Graph API


Microsoft Office365 EWS and Ms Graph API servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.


Create your application in Azure Portal

To use Microsoft/Office365 OAUTH in your application, you must create a application in https://portal.azure.com.


Single tenant and multitenant in account type

When the register an application page appears, enter a meaningful application name and select the account type.

Select which accounts you would like your application to support.

Because we want to support all Office 365 and LIVE SDK (hotmail, outlook personal account), so select Accounts in any organizational directory and personal Microsoft accounts.


API Permission

Now we need to add permission to the application:

Click API Permission -> Add a permission -> Microsoft Graph -> Delegated Permission -> User.Read, email, offline_access, openid, profile, SMTP.Send, IMAP.AccessAsUser.All and Mail.Send. POP.AccessAsUser.All.

EWS API permission

With the above permissions, your application can support SMTP, POP, IMAP and Graph API service. If your application needs to support EWS protocol either, add EWS permission like this:

Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Delegated Permission -> Check EWS.AccessAsUser.All

Here is permissions list:


Authentication and redirect uri


Client Id and client secrets

Now we need to create a client secret for the application, click Certificates and secrets -> client secrets and add a new client secret.

After client secret is created, store the client secret value to somewhere, Please store client secret value by yourself, because it is hidden when you view it at next time.


Branding and verify publisher

Now we click Branding, you can edit your company logo, URL and application name. If your application supports multitenant (access user in all Office 365 and Microsoft personal account), you must complete the publisher verification.

It is not difficult, you can have a look at publisher verification. After publisher verification is completed, your branding is like this:

You must complete the publisher verification for multitenant application, otherwise, your application will not request access token correctly.


Client id and tenant

Now you can click Overview to find your client id and tenant.

If your application is single tenant, use the tenant value in tokenUri and authUri instead of "common". If your application is multitenant, use "common" as tenant.

Above client_id and secret support both "Office365 + SMTP/POP/IMAP/EWS" and "Live (hotmail, outlook personal account) + SMTP/POP/IMAP".


Use client id and client secret to request access token

You can use client id and client secret to get the user email address and access token like this:


Access token expiration and refresh token

You don’t have to open browser to request access token every time. By default, access token expiration time is 3600 seconds, you can use the access token repeatedly before it is expired. After it is expired, you can use refresh token to refresh access token directly without opening browser. You can find full sample project in EASendMail installation path to learn how to refresh token.

You should create your client id and client secret, don't use the client id in the sample project, it is only for test purpose. If you got "This app isn't verified" information, please click "advanced" -> Go to ... for test.

Request access token

[C# - Get access token and user with Microsoft.Identity.Client]
// You can install Microsoft.Identity.Client by NuGet
// Install-Package Microsoft.Identity.Client

using Microsoft.Identity.Client;

var pcaOptions = new PublicClientApplicationOptions
{
    ClientId = "your client id",
    TenantId = "common",
    RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
};

var pca = PublicClientApplicationBuilder
    .CreateWithApplicationOptions(pcaOptions)
    .WithLogging(MyLoggingMethod, LogLevel.Info,
           enablePiiLogging: true,
           enableDefaultPlatformLogging: true).
    Build();

var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All"};
// var ewsScopes = new string[] { "https://graph.microsoft.com/Mail.Send"}; // Ms Graph API scope

// Make the interactive token request
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();

// then you can get access token and user from the following properties
// authResult.AccessToken;
// authResult.Account.Username;

Use access token to send email with Office 365 EWS protocol

After you get user email address and access token, you can use the following codes to send email using Office365 EWS protocol.

Example

[Visual Basic, C#, C++] To get the full samples of EASendMail, please refer to Samples section.

[VB - Send Email using Office 365 OAUTH Authentication]
    
Imports EASendMail

Sub SendMailWithXOAUTH2(userEmail As String, accessToken As String)

    Try
    ' set Office365 EWS server address
        Dim oServer As SmtpServer = New SmtpServer("outlook.office365.com")

    ' set Office365 Ms Graph API server address
    ' Dim oServer As SmtpServer = New SmtpServer("https://graph.microsoft.com/v1.0/me/sendMail")

    ' set Exchange Web Service protocol (EWS) -Office 365 
    oServer.Protocol = ServerProtocol.ExchangeEWS

    ' you can also use Ms Graph API protocol -Office 365 
    ' oServer.Protocol = ServerProtocol.MsGraphApi

    ' set SSL connection
        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto

    ' use  OAUTH 2.0 authentication
        oServer.AuthType = SmtpAuthType.XOAUTH2
    ' set user authentication
        oServer.User = userEmail
    ' use access token as password
        oServer.Password = accessToken

        Dim oMail As SmtpMail = New SmtpMail("TryIt")
        oMail.From = New MailAddress(userEmail)
        oMail.To.Add(New MailAddress("support@emailarchitect.net"))

        oMail.Subject = "test email sent from VB using Office365 OAUTH"
        oMail.TextBody = "test body"

        Dim oSmtp As SmtpClient = New SmtpClient
        oSmtp.SendMail(oServer, oMail)

        Console.WriteLine("The email has been submitted to server successfully!")

    Catch exp As Exception
        Console.WriteLine("Exception: {0}", exp.Message)
    End Try

End Sub
    

[C# - Send Email using Office365 OAUTH Authentication] using System; using EASendMail; void SendMailWithXOAUTH2(string userEmail, string accessToken) { try { // set Office365 EWS server address SmtpServer oServer = new SmtpServer("oultook.office365.com"); // set Office365 Ms Graph API server address // SmtpServer oServer = new SmtpServer("https://graph.microsoft.com/v1.0/me/sendMail"); // set Exchange Web Service protocol (EWS) -Office 365 oServer.Protocol = ServerProtocol.ExchangeEWS; // you can also use Ms Graph API protocol -Office 365 // oServer.Protocol = ServerProtocol.MsGraphApi; // enable SSL connection oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; // use office365 OAUTH 2.0 authentication oServer.AuthType = SmtpAuthType.XOAUTH2; // set user authentication oServer.User = userEmail; // use access token as password oServer.Password = accessToken; SmtpMail oMail = new SmtpMail("TryIt"); oMail.From = userEmail; oMail.To = "support@emailarchitect.net"; oMail.Subject = "test email from Office365 account with OAUTH 2"; oMail.TextBody = "this is a test email sent from c# project with Office365."; Console.WriteLine("start to send email using OAUTH 2.0 ..."); SmtpClient oSmtp = new SmtpClient(); oSmtp.SendMail(oServer, oMail); Console.WriteLine("The email has been submitted to server successfully!"); } catch (Exception ep) { Console.WriteLine("Exception: {0}", ep.Message); } }
[C++/CLI - using Office365 OAUTH Authentication] using namespace System; using namespace EASendMail; void SendMailWithXOAUTH2(String^ userEmail, String^ accessToken) { try { // Office365 server address SmtpServer ^oServer = gcnew SmtpServer("outlook.office365.com"); // set Office365 Ms Graph API server address // SmtpServer ^oServer = gcnew SmtpServer("https://graph.microsoft.com/v1.0/me/sendMail"); // set Exchange Web Service protocol (EWS) -Office 365 oServer->Protocol = ServerProtocol::ExchangeEWS; // you can also use Ms Graph API protocol -Office 365 // oServer->Protocol = ServerProtocol::MsGraphApi; // set SSL connection oServer->ConnectType = SmtpConnectType::ConnectSSLAuto; // use Office365 OAUTH 2.0 authentication oServer->AuthType = SmtpAuthType::XOAUTH2; //set user authentication oServer->User = userEmail; // use access token as password oServer->Password = accessToken; SmtpMail ^oMail = gcnew SmtpMail("TryIt"); oMail->From = gcnew MailAddress(userEmail); oMail->To->Add(gcnew MailAddress("support@emailarchitect.net")); oMail->Subject = "test email sent from C++/CLI using Office365 OAUTH"; oMail->TextBody = "test body"; SmtpClient ^oSmtp = gcnew SmtpClient(); oSmtp->SendMail(oServer, oMail); Console::WriteLine("The email has been submitted to server successfully!"); } catch (System::Exception ^exp) { Console::WriteLine("Exception: {0}", exp->Message); } }

Remarks

If your application is background service which doesn't support user interaction, please have a look at this topic: Use Office365 OAUTH with Background Service.

If you don't want to use OAUTH 2.0, Office 365 also supports traditional user authentication.

Online Tutorial

C# - Send Email using Google/Gmail OAuth 2.0 Authentication
C# - Send Email using Gmail/G Suite OAuth 2.0 in Background Service (Service Account)
C# - Send Email using Microsoft OAuth 2.0 (Modern Authentication) from Hotmail/Outlook Account
C# - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 Account
C# - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

VB - Send Email using Google/Gmail OAuth 2.0 Authentication
VB - Send Email using Gmail/G Suite OAuth 2.0 in Background Service (Service Account)
VB - Send Email using Microsoft OAuth 2.0 (Modern Authentication) from Hotmail/Outlook Account
VB - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 Account
VB - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

C++/CLI - Send Email using Google/Gmail OAuth 2.0 Authentication
C++/CLI - Send Email using Gmail/G Suite OAuth 2.0 in Background Service (Service Account)
C++/CLI - Send Email using Microsoft OAuth 2.0 (Modern Authentication) from Hotmail/Outlook Account
C++/CLI - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 Account
C++/CLI - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

See Also

User Authentication and SSL Connection
Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2
Using Gmail SMTP OAUTH
Using Gmail/GSuite Service Account + SMTP OAUTH Authentication
Using Office365 EWS OAUTH in Background Service
Using Hotmail SMTP OAUTH
Using EASendMail SMTP .NET Component
From, ReplyTo, Sender and Return-Path
DomainKeys and DKIM Signature
Send E-mail Directly (Simulating SMTP server)
Work with EASendMail Service (Email Queuing)
Bulk Email Sender Guidelines
Process Bounced Email (Non-Delivery Report) and Email Tracking
EASendMail .NET Namespace References
EASendMail SMTP Component Samples