Using Microsoft/Office 365 EWS and Ms Graph API OAUTH with Background Service


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.

You can click here to learn more detail about "OAUTH/XOAUTH2 with Office 365 EWS Service" .

Office 365 OAuth 2.0 client credentials grant

Normal OAUTH requires user input user/password for authentication. Obviously, it is not suitable for background service. In this case, You can use the OAuth 2.0 client credentials grant, sometimes called two-legged OAuth, to access web-hosted resources by using the identity of an application. It only works for Office365 user, it doesn't work for personal Hotmail account.


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 just need to support Offic365 user in our organization, so select Accounts in this organizational directory only (single tenant).

Do not select supporting Microsoft personal account, because there is no way to access Microsoft personal account in background service.


API Permission

Click API Permission -> Microsoft Graph -> Delegated Permission -> User.Read; Click API Permission -> Microsoft Graph -> Application Permission -> Mail.Send; Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Application Permission -> Other permission -> full_access_as_app

If your current user is not a user in a verified domain or Offic 365, you will not find Office 365 Exchange Online in API list, then you have to add this API permission manually.

{
    "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
    "resourceAccess": [
        {
            "id": "dc890d15-9560-4a4c-9b7f-a736ec74ec40",
            "type": "Role"
        }
    ]
}
    


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.


Grant admin consent

To use your application to access user mailbox in Office365 domain, you should get admin consent by Office365 domain administrator.

After administrator authorized the permissions, you can use your application to access any users mailbox in Office365 domain.


Use EWS OAUTH 2.0 to send email impersonating user in Office365 domain

The following examples demonstrate how to send email with EWS OAUTH

Example

[C# - Use EWS OAUTH 2.0 to send email impersonating user in Office365 domain]

using System;
using System.Text;
using System.IO;
using System.Net;
using EASendMail;

static string _postString(string uri, string requestData)
{
    HttpWebRequest httpRequest = WebRequest.Create(uri) as HttpWebRequest;
    httpRequest.Method = "POST";
    httpRequest.ContentType = "application/x-www-form-urlencoded";

    using (Stream requestStream = httpRequest.GetRequestStream())
    {
        byte[] requestBuffer = Encoding.UTF8.GetBytes(requestData);
        requestStream.Write(requestBuffer, 0, requestBuffer.Length);
        requestStream.Close();
    }

    try
    {
        HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
        var responseText = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
        Console.WriteLine(responseText);
        return responseText;
    }
    catch (WebException ep)
    {
        if(ep.Status == WebExceptionStatus.ProtocolError)
        { 
            var responseText = new StreamReader(ep.Response.GetResponseStream()).ReadToEnd();
            Console.WriteLine(responseText);
        }

        throw ep;
    }
}

public void SendMail()
{
    try
    {
        string client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f";
        string client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-.";

     // If your application is not created by Office365 administrator, 
     // please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
     // Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
        string tenant = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776";

        string requestData = 
            string.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials",
                client_id, client_secret);

        // use this scope for Ms Graph API
        // string requestData = 
        //    string.Format("client_id={0}&client_secret={1}&scope=https://graph.microsoft.com/Mail.Send&grant_type=client_credentials",
        //            client_id, client_secret);

        string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant);
        string responseText = _postString(tokenUri, requestData);

        OAuthResponseParser parser = new OAuthResponseParser();
        parser.Load(responseText);

        string officeUser = "user@mydomain.onmicrosoft.com";
        
        var server = new SmtpServer("outlook.office365.com");
        server.Protocol = ServerProtocol.ExchangeEWS;

        // use this for Ms Graph API
        // var server = new SmtpServer("https://graph.microsoft.com/v1.0/me/sendMail");
        // server.Protocol = ServerProtocol.MsGraphApi;

        server.User = officeUser;
        
        server.Password = parser.AccessToken;
        server.AuthType = SmtpAuthType.XOAUTH2;
        server.ConnectType = SmtpConnectType.ConnectSSLAuto;

        var mail = new SmtpMail("TryIt");

        mail.From = officeUser;
        mail.To = "support@emailarchitect.net";

        mail.Subject = "Office 365 background service oauth test";
        mail.TextBody = "this is a test, don't reply";

        var smtp = new SmtpClient();
        smtp.SendMail(server, mail);

        Console.WriteLine("Message delivered!");
    }
    catch (Exception ep)
    {
        Console.WriteLine(ep.ToString());
    }
}


[VB.NET - Use EWS OAUTH 2.0 to send email impersonating user in Office365 domain] Imports System Imports System.Text Imports System.Net Imports EASendMail Private Shared Function _postString(ByVal uri As String, ByVal requestData As String) As String Dim httpRequest As HttpWebRequest = TryCast(WebRequest.Create(uri), HttpWebRequest) httpRequest.Method = "POST" httpRequest.ContentType = "application/x-www-form-urlencoded" Using requestStream As Stream = httpRequest.GetRequestStream() Dim requestBuffer As Byte() = Encoding.UTF8.GetBytes(requestData) requestStream.Write(requestBuffer, 0, requestBuffer.Length) requestStream.Close() End Using Try Dim httpResponse As HttpWebResponse = TryCast(httpRequest.GetResponse(), HttpWebResponse) Dim responseText = New StreamReader(httpResponse.GetResponseStream()).ReadToEnd() Console.WriteLine(responseText) Return responseText Catch ep As WebException If ep.Status = WebExceptionStatus.ProtocolError Then Dim responseText = New StreamReader(ep.Response.GetResponseStream()).ReadToEnd() Console.WriteLine(responseText) End If Throw ep End Try End Function Public Sub SendMail() Try Dim client_id As String = "8f54719b-4070-41ae-91ad-f48e3c793c5f" Dim client_secret As String = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-." ' If your application is not created by Office365 administrator, ' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you. ' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory. Dim tenant As String = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776" Dim requestData As String = String.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials", client_id, client_secret) ' use this scope for Ms Graph API ' Dim requestData As String = String.Format("client_id={0}&client_secret={1}&scope=https://graph.microsoft.com/Mail.Send&grant_type=client_credentials", ' client_id, client_secret) Dim tokenUri As String = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant) Dim responseText As String = _postString(tokenUri, requestData) Dim parser As OAuthResponseParser = New OAuthResponseParser() parser.Load(responseText) Dim officeUser As String = "user@mydomain.onmicrosoft.com" Dim server As New SmtpServer("outlook.office365.com") server.Protocol = ServerProtocol.ExchangeEWS ' use this for Ms Graph API ' Dim server As new SmtpServer("https://graph.microsoft.com/v1.0/me/sendMail") ' server.Protocol = ServerProtocol.MsGraphApi server.User = officeUser server.Password = parser.AccessToken server.AuthType = SmtpAuthType.XOAUTH2 server.ConnectType = SmtpConnectType.ConnectSSLAuto Dim mail = New SmtpMail("TryIt") mail.From = officeUser mail.[To] = "support@emailarchitect.net" mail.Subject = "Office 365 background service oauth test" mail.TextBody = "this is a test, do not reply" Dim smtp = New SmtpClient() smtp.SendMail(server, mail) Console.WriteLine("Message delivered!") Catch ep As Exception Console.WriteLine(ep.ToString()) End Try End Sub

Remarks

You don't have to request access token every time, once you get an access token, it is valid within 3600 seconds.

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