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 and Ms Graph API 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 (Ms Graph API); Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Application Permission -> Other permission -> full_access_as_app (EWS)

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

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

Const ConnectNormal = 0
Const ConnectSSLAuto = 1
Const ConnectSTARTTLS = 2
Const ConnectDirectSSL = 3
Const ConnectTryTLS = 4

Const AuthAuto = -1
Const AuthLogin = 0
Const AuthNtlm = 1
Const AuthCramMd5 = 2
Const AuthPlain = 3
Const AuthMsn = 4
Const AuthXoauth2 = 5

Private Function GenerateRequestData() 

    Const client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f"
    Const client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."
    Const scope = "https://outlook.office365.com/.default" ' EWS scope
    'Const scope = "https://graph.microsoft.com/Mail.Send" 'Please use this scope with Ms Graph API

    GenerateRequestData = "client_id=" & client_id & "&client_secret=" & client_secret & "&scope=" & scope & "&grant_type=client_credentials"

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")
    
    ' 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.
    Const tenant_id =  "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"
    
    Dim tokenUri 
    tokenUri = "https://login.microsoftonline.com/" & tenant_id & "/oauth2/v2.0/token"
    
    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData
    
    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop
    
    Dim Status
    Status = httpRequest.Status
    
    If Status < 200 Or Status >= 300 Then
        MsgBox "Failed to get access token from server."
        MsgBox httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText
    
    Dim oauthParser As New EASendMailObjLib.OAuthResponseParser
    oauthParser.Load result
    
    Dim accessToken
    accessToken = oauthParser.AccessToken
    
    If accessToken = "" Then
        MsgBox "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    MsgBox "Failed to request access token." & Err.Description
        
End Function

Private Sub SendEmail()
   
    Dim accessToken As String
    accessToken = RequestAccessToken(GenerateRequestData())

    If accessToken = "" Then
        Exit Sub
    End If

    Dim Office365User As String
    Office365User = "user@mydomain.onmicrosoft.com"

    Dim oSmtp As EASendMailObjLib.Mail
    Set oSmtp = New EASendMailObjLib.Mail
    oSmtp.LicenseCode = "TryIt"

    ' Office365 server address
    oSmtp.ServerAddr = "outlook.office365.com"

    ' Office365 MS Graph API server address
    ' oSmtp.ServerAddr = "https://graph.microsoft.com/v1.0/me/sendMail"

    ' Set Exchange Web Service Protocol - EWS - Exchange 2007/2010/2013/2016/2019/Office365
    oSmtp.Protocol = 1
    
    'oSmtp.Protocol = 4 ' Ms Graph API protocol

    ' Enable SSL/TLS connection
    oSmtp.ConnectType = ConnectSSLAuto

    ' OAUTH/XOAUTH2 type
    oSmtp.AuthType = AuthXoauth2 
    
    oSmtp.UserName = Office365User
    oSmtp.Password = accessToken
    
    oSmtp.FromAddr = Office365User
    oSmtp.AddRecipient "Support Team", "support@emailarchitect.net", 0
    
    oSmtp.BodyText = "Hello, this is a test...."
    If oSmtp.SendMail() = 0 Then
        MsgBox "Message delivered!"
    Else
        MsgBox oSmtp.GetLastErrDescription()
    End If

End Sub


[Visual C++ - Use EWS OAUTH 2.0 to send email impersonating user in Office365 domain] #include "pch.h" #include <tchar.h> #include <Windows.h> #include "EASendMailObj.tlh" using namespace EASendMailObjLib; #include "msxml3.tlh" using namespace MSXML2; const int ConnectNormal = 0; const int ConnectSSLAuto = 1; const int ConnectSTARTTLS = 2; const int ConnectDirectSSL = 3; const int ConnectTryTLS = 4; const int AuthAuto = -1; const int AuthLogin = 0; const int AuthNtlm = 1; const int AuthCramMd5 = 2; const int AuthPlain = 3; const int AuthMsn = 4; const int AuthXoauth2 = 5; BOOL RequestAccessToken(const TCHAR* requestData, _bstr_t &accessToken) { try { IServerXMLHTTPRequestPtr httpRequest = NULL; httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP)); if (httpRequest == NULL) { _tprintf(_T("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n")); return FALSE; } _bstr_t fullRequest = requestData; const char* postData = (const char*)fullRequest; LONG cdata = strlen(postData); LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL); for (LONG k = 0; k < (int)cdata; k++) { BYTE ch = (BYTE)postData[k]; ::SafeArrayPutElement(psaHunk, &k, &ch); } _variant_t requestBuffer; requestBuffer.vt = (VT_ARRAY | VT_UI1); requestBuffer.parray = psaHunk; // 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. const TCHAR* tenant_id = _T("79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"); _variant_t async(true); _bstr_t tokenUri(_T("https://login.microsoftonline.com/")); tokenUri += tenant_id; tokenUri += _T("/oauth2/v2.0/token"); httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056); httpRequest->open(L"POST", tokenUri, async, vtMissing, vtMissing); httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded"); httpRequest->send(requestBuffer); while (httpRequest->readyState != 4) { httpRequest->waitForResponse(1); } long status = httpRequest->status; _bstr_t responseText = httpRequest->responseText; if (status < 200 || status >= 300) { _tprintf(_T("Failed to get access token from server: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } IOAuthResponseParserPtr oauthParser = NULL; oauthParser.CreateInstance(__uuidof(EASendMailObjLib::OAuthResponseParser)); oauthParser->Load(responseText); accessToken = oauthParser->AccessToken; if (accessToken.length() == 0) { _tprintf(_T("Failed to parse access token from server response: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } return TRUE; } catch (_com_error &ep) { _tprintf(_T("Failed to get access token: %s"), (const TCHAR*)ep.Description()); return FALSE; } } _bstr_t GenerateRequestData() { const TCHAR* client_id = _T("8f54719b-4070-41ae-91ad-f48e3c793c5f"); const TCHAR* client_secret = _T("cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."); const TCHAR* scope = _T("https://outlook.office365.com/.default"); //const TCHAR* scope = _T("https://graph.microsoft.com/Mail.Send"); //Please use this scope with Ms Graph API _bstr_t buffer = _T("client_id="); buffer += client_id; buffer += _T("&client_secret="); buffer += client_secret; buffer += _T("&scope="); buffer += scope; buffer += _T("&grant_type=client_credentials"); return buffer; } void SendEmail() { ::CoInitialize(NULL); _bstr_t accessToken; // request access token from MS server without user interaction if (!RequestAccessToken((const TCHAR*)GenerateRequestData(), accessToken)) { return; } const TCHAR* Office365User = _T("user@mydomain.onmicrosoft.com"); IMailPtr oSmtp = NULL; oSmtp.CreateInstance(__uuidof(EASendMailObjLib::Mail)); oSmtp->LicenseCode = _T("TryIt"); // Office365 EWS server address oSmtp->ServerAddr = _T("outlook.office365.com"); // Office365 MS Graph API server address // oSmtp->ServerAddr = _T("https://graph.microsoft.com/v1.0/me/sendMail"); // Set Exchange Web Service Protocol - EWS - Exchange 2007/2010/2013/2016/2019/Office365 oSmtp->Protocol = 1; //oSmtp->Protocol = 4; //Ms Graph API protocol // Enable SSL/TLS connection oSmtp->ConnectType = ConnectSSLAuto; // OAUTH/XOAUTH2 type oSmtp->AuthType = AuthXoauth2; oSmtp->UserName = Office365User; oSmtp->Password = accessToken; oSmtp->FromAddr = Office365User; oSmtp->AddRecipient(_T("Support Team"), _T("support@emailarchitect.net"), 0); oSmtp->BodyText = _T("Hello, this is a test...."); if (oSmtp->SendMail() == 0) _tprintf(_T("Message delivered!")); else _tprintf((const TCHAR*)oSmtp->GetLastErrDescription()); }
[Delphi - Use EWS OAUTH 2.0 to send email impersonating user in Office365 domain] const ConnectNormal = 0; ConnectSSLAuto = 1; ConnectSTARTTLS = 2; ConnectDirectSSL = 3; ConnectTryTLS = 4; AuthAuto = -1; AuthLogin = 0; AuthNtlm = 1; AuthCramMd5 = 2; AuthPlain = 3; AuthMsn = 4; AuthXoauth2 = 5; function TForm1.RequestAccessToken(requestData: WideString): WideString; var httpRequest: TServerXMLHTTP; oauthParser: TOAuthResponseParser; fullRequest: OleVariant; status: integer; responseText: WideString; accessToken: WideString; tokenUri, tenant_id: WideString; begin result := ''; httpRequest := TServerXMLHTTP.Create(Application); fullRequest := requestData; // 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. tenant_id := '79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776'; tokenUri := 'https://login.microsoftonline.com/' + tenant_id + '/oauth2/v2.0/token'; httpRequest.setOption(2, 13056); httpRequest.open('POST', tokenUri, true); httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); httpRequest.send(fullRequest); while( httpRequest.readyState <> 4 ) do begin try httpRequest.waitForResponse(1); Application.ProcessMessages(); except ShowMessage('Server response timeout (access token).'); exit; end; end; status := httpRequest.status; responseText := httpRequest.responseText; if (status < 200) or (status >= 300) then begin ShowMessage('Failed to get access token from server.' + responseText); exit; end; oauthParser := TOAuthResponseParser.Create(Application); oauthParser.Load(responseText); accessToken := oauthParser.AccessToken; if accessToken = '' then begin ShowMessage('Failed to parse access token from server response.'); exit; end; result := accessToken; end; function TForm1.GenerateRequestData(): WideString; const client_id: WideString = '8f54719b-4070-41ae-91ad-f48e3c793c5f'; client_secret: WideString = 'cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-.'; scope: WideString = 'https://outlook.office365.com/.default'; // scope: WideString = 'https://graph.microsoft.com/Mail.Send'; // Ms Graph API scope begin result := 'client_id=' + client_id + '&client_secret=' + client_secret + '&scope=' + scope + '&grant_type=client_credentials'; end; procedure TForm1.SendEmail(); var oSmtp : TMail; accessToken: WideString; Office365User: WideString; begin accessToken := RequestAccessToken(GenerateRequestData()); if accessToken = '' then exit; Office365User := 'user@mydomain.onmicrosoft.com'; oSmtp := TMail.Create(Application); oSmtp.LicenseCode := 'TryIt'; // Office365 EWS server address oSmtp.ServerAddr := 'outlook.office365.com'; // Office365 MS Graph API server address // oSmtp.ServerAddr := 'https://graph.microsoft.com/v1.0/me/sendMail'; // Set Exchange Web Service Protocol - EWS - Exchange 2007/2010/2013/2016/2019/Office365 oSmtp.Protocol := 1; // oSmtp.Protocol := 4; // Set Ms Graph API protocol // Enable SSL/TLS connection oSmtp.ConnectType := ConnectSSLAuto; // OAUTH/XOAUTH2 type oSmtp.AuthType := AuthXoauth2; oSmtp.UserName := Office365User; oSmtp.Password := accessToken; // Set sender email address oSmtp.FromAddr := Office365User; // Add recipient email address oSmtp.AddRecipientEx('support@emailarchitect.net', 0); // Set email subject oSmtp.Subject := 'simple email from Delphi project'; // Set email body oSmtp.BodyText := 'this is a test email sent from Delphi project, do not reply'; ShowMessage('start to send email ...'); if oSmtp.SendMail() = 0 then ShowMessage('email was sent successfully!') else ShowMessage('failed to send email with the following error: ' + oSmtp.GetLastErrDescription()); end; end.

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 Example

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

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

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

See Also

Using EASendMail ActiveX Object
Registration-free COM with Manifest File
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
From, ReplyTo, Sender and Return-Path
Digital Signature and Email Encryption - S/MIME
DomainKeys Signature and DKIM Signature
Send Email without SMTP server(DNS lookup)
Work with EASendMail Service(Mail Queuing)
Programming with Asynchronous Mode
Programming with FastSender
Mail vs. FastSender
Bulk Email Sender Guidelines
Process Bounced Email (Non-Delivery Report) and Email Tracking
Work with RTF and Word
EASendMail ActiveX Object References
EASendMail SMTP Component Samples