Connect to Exchange Online SMTP with the client credentials flow

Updated:

Warning

This sample is preserved as a historical record. It accepts all certificates and prints authentication data containing an access token to the console. Do not run it as written. Validate certificates, avoid logging authentication data, and manage secrets securely in your implementation.

Note

Azure Active Directory is now called Microsoft Entra ID. The app registration steps are based on the portal interface at the time of writing. .NET 7, used to test the sample, is out of support.

The client credentials flow is now supported for SMTP. Developer information is available on the following page:

Authenticate an IMAP, POP or SMTP connection using OAuth

This article introduces app registration, Exchange Online configuration, and a basic C# implementation. The code itself is not explained, so please read it alongside the developer documentation above. It implements only the minimum functionality; a full implementation requires knowledge of the Microsoft identity platform and SMTP. The sample is a C# console application that uses MSAL for authentication.

If you do not have a clear requirement to connect to Exchange Online using SMTP, consider migrating to Microsoft Graph instead.

For the device authentication grant flow, see Connect to Exchange Online SMTP with OAuth.

Register the app

  1. Go to the Azure portal and sign in.
  2. Go to the Azure Active Directory blade.
  3. Select Manage > App registrations > New registration.
  4. Configure the following settings and select Register:
    • Name: Enter any application name (for example, SmtpTest02).
    • Supported account types: Accounts in any organizational directory (any Azure AD directory - multitenant).
    • Redirect URI: Select Public client/native (mobile & desktop) from the drop-down list and enter https://login.microsoftonline.com/common/oauth2/nativeclient.
  5. Under Overview > Essentials, record the Application (client) ID.
  6. Select Manage > API permissions.
  7. Select Add a permission.
  8. Under APIs my organization uses, select Office 365 Exchange Online.
  9. Select Application permissions.
  10. Select SMTP > SMTP.SendAsApp, and then select Add permissions.
  11. Under Configured permissions, select the ellipsis next to the default Microsoft Graph > User.Read permission, and then select Remove permission.
  12. Select Yes, remove.
  13. Select Grant admin consent for <tenant name>.
  14. Select Yes.
  15. Select Manage > Certificates & secrets.
  16. Under Client secrets, select New client secret.
  17. Enter a description and select Add.
  18. Record the value of the new client secret.
  19. Return to the top of the Azure Active Directory blade.
  20. Select Manage > Enterprise applications.
  21. Find the app you registered in the list and record its Object ID.

Configure Exchange Online

  1. Connect to Exchange Online from PowerShell with Exchange Online administrator permissions.

  2. Run the following command:

    1
    New-ServicePrincipal -AppId <application (client) ID recorded above> -ObjectId <object ID recorded above> -DisplayName <registered app name> | fl

    Example:

    1
    New-ServicePrincipal -AppId 05cd6963-153d-437f-92c7-2ddbc195d595 -ObjectId 8e1edc86-3a23-4afa-99d9-0cc0794b123d -DisplayName "SmtpTest02" | fl
  3. Run the following command to grant the app full access to the mailbox it will connect to:

    1
    Add-MailboxPermission -Identity <target mailbox> -User <Identity value in the output of New-ServicePrincipal in step 2> -AccessRights FullAccess

    Example:

    1
    Add-MailboxPermission -Identity ExoUser01 -User 8e1edc86-3a23-4afa-99d9-0cc0794b123d -AccessRights FullAccess

Sample code

The sample was tested with MSAL (Microsoft.Identity.Client) version 4.54.1 on .NET 7.0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
using Microsoft.Identity.Client;
using System.Net.Security;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace SmtpOAuthCcfDemo
{
internal class Program
{
private const string ClientId = "<APPLICATION (CLIENT) ID RECORDED ABOVE>";
private const string Secret = "<CLIENT SECRET RECORDED ABOVE>";
private const string TenantId = "<TENANT NAME (e.g. contoso.onmicrosoft.com)>";
private static readonly string[] Scopes = new string[] { "https://outlook.office365.com/.default" };

private const string SenderSmtpAddress = "<SENDER SMTP ADDRESS (MAILBOX THE APP HAS FULL ACCESS TO)>";
private const string RecipientSmtpAddress = "<RECIPIENT SMTP ADDRESS>";

static void Main(string[] args)
{
var tokenResult = GetToken().Result;
string token = tokenResult.AccessToken;
string XOAUTH2 = Base64Encode($"user={SenderSmtpAddress}\u0001auth=Bearer {token}\u0001\u0001");

using (ExoSmtpClient client = new())
{
// Receive the greating.
var response = client.Receive();

if (!response.StartsWith("220"))
{
throw new Exception("Unexpected response received.");
}

client.Send($"EHLO {Dns.GetHostName()}");
response = client.Receive();

if (!response.Contains("STARTTLS"))
{
throw new Exception("STARTTLS is not supported");
}

client.Send("STARTTLS");
response = client.Receive();

if (!response.StartsWith("220"))
{
throw new Exception("Unexpected response received.");
}

client.UpgradeToSsl();

client.Send($"EHLO {Dns.GetHostName()}");
response = client.Receive();

if (!response.Contains("XOAUTH2"))
{
throw new Exception("OAuth is not supported");
}

client.Send("AUTH XOAUTH2");
response = client.Receive();

if (!response.StartsWith("334"))
{
throw new Exception("Unexpected response received.");
}

client.Send(XOAUTH2);
response = client.Receive();

if (!response.StartsWith("235"))
{
throw new Exception("Authentication failure");
}

client.Send($"MAIL FROM: {SenderSmtpAddress}");
response = client.Receive();

if (!response.StartsWith("250"))
{
throw new Exception("Unexpected response received.");
}

client.Send($"RCPT TO: {RecipientSmtpAddress}");
response = client.Receive();

if (!response.StartsWith("250"))
{
throw new Exception("Unexpected response received.");
}

client.Send("DATA");
response = client.Receive();

if (!response.StartsWith("354"))
{
throw new Exception("Unexpected response received.");
}

client.Send($"From: {SenderSmtpAddress}");
client.Send($"To: {RecipientSmtpAddress}");
client.Send("Subject: Test Mail");
client.Send("");
client.Send("Test message.");
client.Send(".");

response = client.Receive();

if (!response.StartsWith("250"))
{
throw new Exception("Unexpected response received.");
}

client.Send("QUIT");
}

Console.ReadLine();
}

static async Task<AuthenticationResult> GetToken()
{
var cca = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(Secret)
.Build();

return await cca.AcquireTokenForClient(Scopes)
.WithAuthority(AzureCloudInstance.AzurePublic, TenantId)
.ExecuteAsync();
}

private static string Base64Encode(string plainText)
{
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
}

public class ExoSmtpClient : TcpClient
{
private Stream stream;
private readonly string host = "outlook.office365.com";
private byte[] receiveBuffer = new byte[1024];

public ExoSmtpClient()
: base("outlook.office365.com", 587)
{
stream = GetStream();
}

public void UpgradeToSsl()
{
var sslStream = new SslStream(stream, false, ValidateRemoteCertificate);
sslStream.AuthenticateAsClient(host);
stream = sslStream;
}

private static bool ValidateRemoteCertificate(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}

public void Send(string command)
{
var commandBytes = Encoding.ASCII.GetBytes(command + Environment.NewLine);
stream.Write(commandBytes, 0, commandBytes.Length);

Console.WriteLine($"C:\t{command}");
}

public string Receive()
{
var stringBuilder = new StringBuilder();

for (; ; )
{
var temp = stream.Read(receiveBuffer, 0, receiveBuffer.Length);
stringBuilder.Append(Encoding.ASCII.GetString(receiveBuffer, 0, temp));

if (0 < Available)
{
continue;
}

if (2 <= stringBuilder.Length && stringBuilder[stringBuilder.Length - 2] == '\r' && stringBuilder[stringBuilder.Length - 1] == '\n')
{
break;
}
}

var response = stringBuilder.ToString();

Console.WriteLine($"S:\t{stringBuilder.Replace("\r\n", "\r\n\t").ToString(0, stringBuilder.Length - 1)}");

return response;
}
}
}

Advertisement