VB.NET/ASP.NET/ASP MVC - Send Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

You can send email using traditional user/password authentication from Office 365 account by EWS Protocol.

However Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.

Installation

Before you can use the following codes, please download EASendMail SMTP Component and install it on your machine at first. Full sample proejcts are included in this installer.

Install from NuGet

You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:

Install-Package EASendMail

Note

If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.

Add Reference

To use EASendMail SMTP Component in your project, the first step is Add reference of EASendMail to your project. Please create or open your project with Visual Studio, then go to menu -> Project -> Add Reference -> .NET -> Browse..., and select Installation Path\Lib\net[version]\EASendMail.dll from your disk, click Open -> OK, the reference of EASendMail will be added to your project, and you can start to use it to send email in your project.

add reference in c#/vb.net/c++/cli/clr

.NET Assembly

Because EASendMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.

Separate builds of run-time assembly for .NET Framework 1.1, 2.0, 3.5, 4.0, 4.5, 4.6.1, .NET Core 2.1 and .NET Compact Framework 2.0, 3.5.

File .NET Framework Version
Lib\net11\EASendMail.dll Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version.
Lib\net20\EASendMail.dll Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version.
Lib\net35\EASendMail.dll Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version.
Lib\net40\EASendMail.dll Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version.
Lib\net45\EASendMail.dll Built with .NET Framework 4.5
It requires .NET Framework 4.5 or later version.
Lib\net461\EASendMail.dll Built with .NET Framework 4.6.1
It requires .NET Framework 4.6.1 or later version.
Lib\netcoreapp2.1\EASendMail.dll Built with .NET Core 2.1
It requires .NET Core 2.1 or later version.
Lib\net20-cf\EASendMail.dll Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version.
Lib\net35-cf\EASendMail.dll Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version.

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/Live OAuth (Modern Authentication) in your application, you must create a application in https://portal.azure.com.

Important

You can use any Microsoft user to create the application, it doesn’t require application owner is administrator in your Office365 domain. But your Office365 administrator must authorize the application to access user mailbox.

  • Sign in to the Azure portal using either a work or school account or a personal Microsoft account.

  • If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the Azure AD tenant that you want.

  • In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations -> New registration.

    azure portal new app registration
  • When the Register an application page appears, enter your application’s registration information:

    azure portal app registration information
    • Name - Enter a meaningful application name that will be displayed to users of the app.
    • Supported account types - Select which accounts you would like your application to support. Because we need to support all Office 365 and LIVE SDK (hotmail, outlook personal account) select Accounts "in any organizational directory and personal Microsoft accounts".
  • Redirect URI (optional)

    Select the type of app you’re building, Web or Public client (mobile & desktop), and then enter the redirect URI (or reply URL) for your application.

    For web applications, provide the base URL of your app. For example, http://localhost:31544 might be the URL for a web app running on your local machine. Users would use this URL to sign in to a web client application.

    For public client applications, provide the URI used by Azure AD to return token responses. Enter a value specific to your application, such as myapp://auth.

  • Client Id/secrets

    After you registered your application, Azure AD assigns a unique application (client) ID to your app, and you’re taken to your application’s Overview page. click "Certificates and secrets" -> "client secrets" and add a new client secret.

Important

Please store "client secret" by yourself, because it is hidden when you view it at next time.

API Permission

Click "API Permission" -> "Add a permission" -> "Exchange" -> "Application permissions" -> "Check full_access_as_app" -> "Add a permission" -> "Microsoft Graph" -> "Delegated Permission" -> "User.Read", "email", "offline_access", "openid" and "profile".

azure app api permission

Authentication

  • Click "Authentication"

    • Implicit grant: check "Access tokens" and "ID tokens";
    • Redirect URI: input the url to get authorization code, for native desktop application, you don’t have to add redirect uri.
  • Mobile and desktop applications -> Redirect Uri, please check or add the following URI.

    https://login.microsoftonline.com/common/oauth2/nativeclient
    https://login.live.com/oauth20_desktop.srf
    http://127.0.0.1
    

    Note

    • https://login.live.com/oauth20_desktop.srf is used for Live SDK, http://127.0.0.1 is used for local Http Listener.
  • Supported account types:

    Select Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)

  • Advanced settings:

    Set both "Live SDK Support" and "Treat application as a public client" to "Yes".

azure app authentication Overview

Above client id and client secret support both "Office365 + EWS" and "Live (hotmail, outlook personal account) + SMTP", Office365 OAuth doesn’t support SMTP, only EWS is supported.

VB.NET/ASP.NET/ASP MVC - Send Email using Microsoft OAuth 2.0 from Office 365 Account in Background Service - Example

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)
        Using reader As New StreamReader(httpResponse.GetResponseStream())
            Dim responseText = reader.ReadToEnd()
            Return responseText
        End Using

    Catch ex As WebException

        If ex.Status = WebExceptionStatus.ProtocolError Then
            Dim response = TryCast(ex.Response, HttpWebResponse)
            If response IsNot Nothing Then
                Console.WriteLine("HTTP: " & response.StatusCode)
                ' reads response body
                Using reader As StreamReader = New StreamReader(response.GetResponseStream())
                    Dim responseText As String = reader.ReadToEnd()
                    Console.WriteLine(responseText)
                End Using
            End If
        End If

        Throw ex
    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)

        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 = New SmtpServer("outlook.office365.com")
        server.Protocol = ServerProtocol.ExchangeEWS

        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

TLS 1.2 Protocol

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.