Reimaginate.Orchestrator.Exchange
1.1.13
dotnet add package Reimaginate.Orchestrator.Exchange --version 1.1.13
NuGet\Install-Package Reimaginate.Orchestrator.Exchange -Version 1.1.13
<PackageReference Include="Reimaginate.Orchestrator.Exchange" Version="1.1.13" />
<PackageVersion Include="Reimaginate.Orchestrator.Exchange" Version="1.1.13" />
<PackageReference Include="Reimaginate.Orchestrator.Exchange" />
paket add Reimaginate.Orchestrator.Exchange --version 1.1.13
#r "nuget: Reimaginate.Orchestrator.Exchange, 1.1.13"
#:package Reimaginate.Orchestrator.Exchange@1.1.13
#addin nuget:?package=Reimaginate.Orchestrator.Exchange&version=1.1.13
#tool nuget:?package=Reimaginate.Orchestrator.Exchange&version=1.1.13
Reimaginate.Orchestrator.Exchange
Read-only Microsoft 365 / Exchange Online mailbox actions for Orchestrator hosts, using Microsoft Graph v1.0. User and shared mailboxes are supported through host-provided application access. For mailbox-limited access, grant the application the scoped Exchange Application Mail.Read role using the administrator setup below. A separate tenant-wide Graph Mail.Read consent is not required for this route.
Every action reads a single resource or one page and returns. The pack does not poll, schedule work, start workflows, publish events, manage webhook subscriptions, store cursors, or modify mailboxes. A separate process owns monitoring, deduplication, and workflow triggering.
Registration
services.AddExchangeWorkflowActions(configuration);
services.AddSingleton<IExchangeWorkflowConnectionProvider, CustomerExchangeConnectionProvider>();
The host implements IExchangeWorkflowConnectionProvider.GetConnectionAsync(tenantKey, mailboxKey, cancellationToken), returning an ExchangeWorkflowConnection with a fresh AccessToken and the resolved MailboxId (preferably the canonical Graph user ID). The keys are logical aliases, not credentials. The host owns OAuth, token refresh, tenant isolation, and mailbox authorization. Tokens are never workflow action inputs or outputs.
Scan the action assembly in the host's resolver:
using Reimaginate.Orchestrator.Abstractions;
using Reimaginate.Orchestrator.Exchange.Actions;
[WorkflowActionResolver]
[ScanAssembly(typeof(ExchangeWorkflowActionsMarker))]
public partial class WorkflowActionResolver : IWorkflowActionResolver;
Registration preserves a host-provided IExchangeClient and connection provider. The public client can also be called by a separate monitoring process without invoking a workflow.
Administrator setup
This setup grants an unattended application read access to one approved Exchange Online mailbox. Run the administrator commands separately from Orchestrator; the action pack never provisions permissions.
1. Register the application and its credential
In Microsoft Entra ID, create or select an app registration in the mailbox's tenant. Record the directory/tenant ID, application/client ID, and the associated Enterprise Application object ID. The object ID on the App Registrations page is a different object.
Configure a certificate or federated credential for the host, or a client secret where required. Keep the private key or secret in the host's credential store. The connection provider obtains tokens for https://graph.microsoft.com/.default using the client credentials flow and caches/reacquires them as needed. See Microsoft's app-only authentication guidance.
2. Grant access to the approved mailbox
Use Exchange RBAC for Applications for mailbox-scoped authorization through Graph. It replaces legacy Application Access Policies; this setup does not also require one. Use an authorized Exchange administrator with the delegating role assignments described in Microsoft's Application RBAC requirements.
Using the Exchange Online Management PowerShell module, replace the example values and run:
Connect-ExchangeOnline
$exchangeClientId = '<application-client-id>'
$exchangeServicePrincipalId = '<enterprise-application-object-id>'
$exchangeAllowedMailbox = 'accounts@example.com'
$exchangeScopeName = 'Orchestrator-Accounts-Read'
# Create the Exchange pointer once; reuse it if this app is already registered.
New-ServicePrincipal -AppId $exchangeClientId -ObjectId $exchangeServicePrincipalId -DisplayName 'Orchestrator Exchange Reader'
$exchangeMailbox = Get-Mailbox -Identity $exchangeAllowedMailbox -ErrorAction Stop
$exchangeMailboxId = [guid]$exchangeMailbox.ExternalDirectoryObjectId
$exchangeScopeFilter = "ExternalDirectoryObjectId -eq '$exchangeMailboxId'"
New-ManagementScope -Name $exchangeScopeName -RecipientRestrictionFilter $exchangeScopeFilter
# Review membership before granting the role: only the approved mailbox should appear.
Get-Recipient -Filter $exchangeScopeFilter | Select-Object DisplayName, PrimarySmtpAddress, ExternalDirectoryObjectId
New-ManagementRoleAssignment -Name 'Orchestrator-Accounts-MailRead' -App $exchangeServicePrincipalId -Role 'Application Mail.Read' -CustomResourceScope $exchangeScopeName
This uses the mailbox's directory object ID so the scope does not depend on its email address. Use a reviewed scope covering the required mailboxes for multi-mailbox installations. Command references: New-ServicePrincipal, New-ManagementScope, filterable properties, and New-ManagementRoleAssignment.
The Application Mail.Read role covers bodies and attachments. Review any existing Entra mail application grants: an unscoped grant can retain broader access because Exchange RBAC and Entra grants are additive. Adding this scope does not narrow an existing tenant-wide Mail.Read grant. See Microsoft's authorization interoperability explanation.
3. Verify allowed and excluded mailboxes
Test-ServicePrincipalAuthorization -Identity $exchangeServicePrincipalId -Resource $exchangeAllowedMailbox
Test-ServicePrincipalAuthorization -Identity $exchangeServicePrincipalId -Resource 'excluded@example.com'
For Application Mail.Read, expect InScope to be true for the approved mailbox and false for the excluded mailbox. This test excludes separate Entra grants, so also test real Graph calls with the application's token: reading the approved mailbox must succeed and the excluded mailbox must be denied. RBAC permission changes can take 30 minutes to two hours to propagate. See Microsoft's authorization testing and limitations.
4. Configure the host connection provider
Give the host administrator the tenant ID, client ID, credential reference, and $exchangeMailboxId. Implement and register IExchangeWorkflowConnectionProvider as described above. Map logical keys such as tenantKey: default and mailboxKey: accounts to that configuration; return a valid Graph token and canonical mailbox ID on each action call. Workflow keys select connections; Microsoft permissions enforce mailbox access.
If the separate polling process uses a different application identity, authorize that identity separately. Its scheduling, cursor storage, and workflow-triggering configuration remain outside this pack.
Actions
All requests require tenantKey and mailboxKey. Responses include success and failureReason, plus action-specific fields. HTTP failures also expose statusCode, graphErrorCode, and, when supplied, retryAfterSeconds. Failures during an HTTP request include clientRequestId and an available valid Graph graphRequestId for support correlation. Caller cancellation propagates to the caller.
| Action | Inputs beyond connection keys | Result |
|---|---|---|
Exchange.ListFolders |
Optional parentFolderId, includeHiddenFolders, top, select, nextLink |
folders, nextLink; lists root folders or a parent's immediate children |
Exchange.GetFolder |
folderId |
folder |
Exchange.SearchMessages |
Optional folderId, filter, search, orderBy, select, top, nextLink |
messages, nextLink; searches a folder or the mailbox |
Exchange.GetMessage |
messageId, optional bodyContentType (text, the default, or html) |
message, including its body |
Exchange.ListAttachments |
messageId, optional top, nextLink |
Attachment metadata in attachments, plus nextLink; never downloads attachment bytes |
Exchange.GetAttachment |
messageId, attachmentId |
attachment metadata and contentBase64 for file or item attachments; reference attachments return metadata only |
Exchange.GetMessageChanges |
Optional folderId (default inbox), cursor, changeType, select, top |
changes, nextLink, deltaLink, resetRequired |
Folder inputs accept Graph folder IDs or well-known names such as inbox. Message and attachment IDs use Graph immutable identifiers and are case-sensitive. Selected properties outside the typed models are retained in AdditionalFields. Message searches and change queries return metadata by default; use GetMessage to retrieve the body.
filter, search, orderBy, and select use Graph's OData/KQL syntax, not a separate query language. search cannot be combined with filter or orderBy. Graph's restrictions on combined filtering and ordering still apply. top is a page-size request from 1 to 1000, not a promise to return all matching items.
Use the returned nextLink unchanged on the next invocation. Keep the same mailbox, folder/parent, and message inputs, and omit the original query options (top, select, filters, search, ordering, hidden-folder flag). Continuation links are restricted to the same Graph collection; redirects are disabled for the default HTTP client.
Reading an email and its attachments
The external monitoring process can pass TenantKey, MailboxKey, and MessageId into a workflow:
do:
- readEmail:
call: Exchange.GetMessage
with:
tenantKey: ${TenantKey}
mailboxKey: ${MailboxKey}
messageId: ${MessageId}
bodyContentType: text
- listAttachments:
call: Exchange.ListAttachments
with:
tenantKey: ${TenantKey}
mailboxKey: ${MailboxKey}
messageId: ${MessageId}
Search messages using a received date and sender:
do:
- findInvoices:
call: Exchange.SearchMessages
with:
tenantKey: default
mailboxKey: accounts
folderId: inbox
filter: "receivedDateTime ge 2026-10-01T00:00:00Z and from/emailAddress/address eq 'invoices@example.test'"
orderBy: receivedDateTime desc
top: 50
Reading changes without polling inside an action
GetMessageChanges is a stateless wrapper around Graph's per-folder delta query. It performs one page request; it does not loop or wait for future mail.
- Call without
cursorto begin synchronisation. The initial pages describe existing folder contents, not exclusively new arrivals. - If
nextLinkis returned, pass it ascursoron a later call for the next page. OmitselectandchangeTypeon cursor requests.topcontrols thePrefer: odata.maxpagesizeheader and can also be supplied with a cursor; it never adds$topto a delta query. - Once
deltaLinkis returned, the round is complete. Store that link externally and pass it ascursorwhen the external process next checks the folder. - The external process decides whether to suppress initial results, when to check again, how to deduplicate observations, and which workflows to start.
do:
- readChanges:
call: Exchange.GetMessageChanges
with:
tenantKey: default
mailboxKey: accounts
folderId: inbox
cursor: ${SavedGraphCursor}
changeType can be created, updated, or deleted on an initial request. Without it, Graph returns all observed changes. Entries with removed / isRemoved represent removal from the monitored folder, which can mean deletion or a move. Other entries contain the current message properties; the action does not infer created versus updated. Multiple edits can be combined, results can repeat, and order is not guaranteed. This is change tracking rather than an audit history.
An expired/invalid synchronisation state returns success: false, failureReason: EXCHANGE_SYNC_STATE_EXPIRED, and resetRequired: true. The pack does not silently reset the cursor. The caller owns resynchronisation and reconciliation. Other failures do not advance any cursor. A message deleted before retrieval may no longer be readable; the external process must capture content earlier if required.
Limits and retries
Configure limits under Orchestrator:Actions:Exchange, or configure ExchangeActionOptions through DI:
{
"Orchestrator": {
"Actions": {
"Exchange": {
"MaxAttachmentBytes": 10485760,
"MaxJsonResponseBytes": 16777216,
"RetryCount": 2,
"MaxRetryDelaySeconds": 5,
"RequestTimeoutSeconds": 100,
"DownloadTimeoutSeconds": 60
}
}
}
}
Limits apply to actual streamed bytes, including responses without Content-Length. File attachments return their file bytes; item attachments return Graph's raw MIME representation. Reference attachments do not fetch linked cloud files.
RequestTimeoutSeconds bounds one HTTP operation, including connection/headers, retries, retry delays, and reading the response body. DownloadTimeoutSeconds additionally bounds each complete body read, including JSON and error responses; the earlier deadline wins. Both settings accept 1..3600 seconds. The registered HTTP client uses these deadlines without an additional HttpClient.Timeout cap. If supplying your own client, its timeout can impose an earlier deadline. GetAttachment makes separate metadata and content requests, each with its own request deadline. Token acquisition remains the connection provider's responsibility.
A request deadline returns EXCHANGE_REQUEST_TIMEOUT; a body deadline returns EXCHANGE_DOWNLOAD_TIMEOUT. An already received HTTP error can still be returned if its diagnostic body cannot be read within the body deadline. Caller cancellation continues to throw OperationCanceledException. Streams and responses are disposed on success, failure, timeout, and cancellation. Body-read failures are not automatically retried. Concurrent reads have independent deadlines and buffers; hosts control their concurrency and memory budget.
Transient network errors and HTTP 408/429/500/502/503/504 responses receive bounded retries. A Graph Retry-After longer than MaxRetryDelaySeconds is returned to the caller immediately rather than retried early or held inside the action. The caller controls later retries. Authentication and permission failures are returned without token refresh attempts.
Operational diagnostics
The pack uses the host's ILogger providers under Reimaginate.Orchestrator.Exchange. Diagnostics contain fixed operation/failure categories, elapsed time, retry delay/count, HTTP status, and generated client/validated Graph request IDs. Each HTTP attempt sends a fresh client-request-id; Graph's request-id is retained only when it is a valid GUID. Error messages and exception objects are never passed to the logger.
| Event ID | Name | Level |
|---|---|---|
| 7100 | ExchangeRequestSucceeded |
Debug |
| 7101 | ExchangeRequestRetry |
Warning |
| 7102 | ExchangeRequestFailed |
Warning |
| 7103 | ExchangeActionFailed |
Warning for missing connection configuration; Error for unexpected/provider failures |
| 7104 | ExchangeRequestCanceled |
Debug |
| 7105 | ExchangeActionReadFailed |
Warning |
Logs exclude access tokens, connection keys, mailbox/message/attachment identifiers, subjects, bodies, attachment bytes, Graph error text, URLs, query strings, and cursors. The default factory logging for this pack's named HTTP client is removed because it would log request URLs. Host-added HTTP handlers, telemetry, and custom client implementations must apply their own redaction policy. Enable Debug for this category when successful request IDs are needed.
Local mailbox tests
ExchangeMailboxLiveTests exercises all seven actions against a dedicated shared mailbox and verifies that the test app cannot read a different mailbox. They run with the normal test suite when local credentials are configured, and they only read mailbox data. Missing or blank required settings cause an xUnit skip with a reason listing the missing setting names; credential values are never included. Configured credentials that are invalid or expired, and Graph request failures, fail the tests rather than skipping them.
Provision the mailbox and scoped application using the administrator setup above. Using a separate sender, seed two synthetic messages with subjects Orchestrator Exchange local test - plain message and Orchestrator Exchange local test - attachment message. The attachment message's body must contain Synthetic mailbox fixture. Attach orchestrator-fixture.txt with these UTF-8 contents (including the final newline):
Orchestrator Exchange local attachment fixture.
Synthetic test data only.
In the unit-test project's .NET user secrets, configure the following keys. The credential must belong to the dedicated scoped test application; no credential belongs in tracked files.
| Key | Value |
|---|---|
ExchangeLiveTest:TenantId |
Microsoft Entra tenant ID |
ExchangeLiveTest:ClientId |
Dedicated test application's client ID |
ExchangeLiveTest:ClientSecret |
Expiring credential for that application |
ExchangeLiveTest:MailboxId |
Canonical directory ID of the test shared mailbox |
ExchangeLiveTest:ExcludedMailboxId |
Canonical directory ID of an existing mailbox outside the app's scope; required only for the access-denial test |
ExchangeLiveTest:SubjectPrefix |
Optional; defaults to Orchestrator Exchange local test |
Environment variables with __ in place of : override user-secret settings. The first four settings are required for every live test. If only ExcludedMailboxId is missing, the two mailbox-reading tests still run and the access-denial test skips with a clear reason. No special runner flag is required; to run just these tests locally:
dotnet build test/Reimaginate.Orchestrator.Test.Unit/Reimaginate.Orchestrator.Test.Unit.csproj
dotnet test/Reimaginate.Orchestrator.Test.Unit/bin/Debug/net10.0/Reimaginate.Orchestrator.Test.Unit.dll -class '*ExchangeMailboxLiveTests' -noLogo -noColor
The tests do not create, send, move, mark, or delete messages. They read the initial delta pages, reuse the returned cursor without waiting for future changes, and perform eight downloads of the synthetic file attachment with concurrency limited to four. Hosts should likewise limit requests per app/mailbox in line with Microsoft's Outlook throttling limits; the pack reports throttling rather than scheduling later work. Wait for mailbox provisioning and authorization propagation before running the tests against a newly created mailbox. Rotate the test credential when it expires.
ExchangeClientReliabilityTests adds deterministic transport tests for stalled headers/bodies, caller cancellation, retry deadlines, safe diagnostic fields, 2,500-entry message/delta pagination, mixed attachment pages, binary/empty/inline files, attached mail/contact/calendar MIME, reference/unsupported attachments, and twelve concurrent 256 KiB downloads. It also verifies that a stalled download does not cancel healthy concurrent downloads. These tests do not require mailbox credentials; simulated batch/concurrency checks are not a production throughput benchmark.
Graph documentation: list messages, get message, folder delta queries, attachment retrieval, and immutable identifiers.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- FluentValidation (>= 12.2.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.14)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Http (>= 10.0.14)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Options (>= 10.0.14)
- Reimaginate.Mediator.Abstractions (>= 1.3.0)
- Reimaginate.Mediator.SourceGenerator (>= 1.3.0)
- Reimaginate.Orchestrator.Abstractions (>= 1.1.13)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.13 | 85 | 11/2/2026 |