Connect an app to Outlook
Receive an Outlook event at a protected app, then flag the matching test message with the connector SDK. An Azure Connector Namespace (preview), the Azure resource that hosts connectors and their authenticated connections, handles polling and authenticated delivery; see managed connectors.
Use harmless messages and an isolated resource group in West US 2 (westus2). Connector polling, actions, and mailbox licensing can incur charges outside the preview offer.
Prerequisites
- An Azure subscription with a Builder target that supports Node.js 24 and Connector Namespace availability.
- Bash, Azure CLI with Bicep, Node.js 24, Python 3, and
jq. - Permission to deploy a resource group and to create an API registration, service principal, federation, and app-role assignments.
- A GitHub account and an Outlook test-mailbox owner who can approve OAuth consent.
1. Prepare your fork and subscription
Fork the sample, then clone it:
git clone "<your-fork-https-url>" builder-outlook
cd builder-outlook
npm ci
npm test
npm run test:infra
Run every block in order, in the same Bash session, from this directory; after a failure, check the existing operation before repeating creation commands. RUN keeps names unique:
export SUBSCRIPTION_ID="<your-subscription-guid>"
export TENANT_ID="<your-tenant-guid>"
export LOCATION="westus2"
export RUN="$(node -p "require('node:crypto').randomBytes(4).toString('hex')")"
export RG="rg-builder-connectors-$RUN"
az login --tenant "$TENANT_ID"
az account set --subscription "$SUBSCRIPTION_ID"
az account show --query '{subscription:id,tenant:tenantId,state:state}'
test "$(az account show --query tenantId -o tsv)" = "$TENANT_ID" || exit 1
test "$(az group exists --subscription "$SUBSCRIPTION_ID" --name "$RG")" = false || exit 1
mkdir -p .local
chmod 700 .local
Keep .local/ out of Git and don't publish tokens or consent links.
2. Create the Azure resources
The template creates an empty app, a Connector Namespace, and three identities (app, sender, unauthorized control):
az group create --subscription "$SUBSCRIPTION_ID" --name "$RG" --location "$LOCATION"
az deployment group validate --subscription "$SUBSCRIPTION_ID" --resource-group "$RG" \
--template-file infra/main.bicep --parameters run="$RUN" location="$LOCATION"
az deployment group what-if --subscription "$SUBSCRIPTION_ID" --resource-group "$RG" \
--template-file infra/main.bicep --parameters run="$RUN" location="$LOCATION"
az deployment group create --subscription "$SUBSCRIPTION_ID" --resource-group "$RG" \
--name connector-sample --template-file infra/main.bicep --parameters run="$RUN" location="$LOCATION"
az deployment group show --subscription "$SUBSCRIPTION_ID" --resource-group "$RG" \
--name connector-sample --query properties.outputs.configuration.value > .local/context.json
3. Protect the callback and configure the connection
- Namespace delivers an event
The namespace sender identity obtains a token for the app API. Required Entra sign-in restricts the allowed tenant and sender principal before the app receives the callback.
- App checks the event
The receiver enforces the exact synthetic-message filter, expiry, and operation bounds. An unrelated control message must not trigger the action.
- App performs the action
The app's different managed identity calls the connector runtime under the connection access policy. The mailbox owner's OAuth connection separately authorizes mailbox access.
Verify independently: Connected status, an allowed authenticated callback, and a successful matching-message action are different results. Check that the matching test item is flagged, the control is unchanged, and the trigger is disabled when the bounded test ends.
Require Entra auth before connecting source, so only the namespace sender can call the public callback.
Register the receiver API
export ROLE_ID="$(node -p "require('node:crypto').randomUUID()")"
export SERVICE_TREE_REFERENCE=""
node scripts/config.mjs registration "$RUN" "$ROLE_ID" "$SERVICE_TREE_REFERENCE" > .local/registration.json
az rest --method post --url https://graph.microsoft.com/v1.0/applications \
--body @.local/registration.json > .local/application.json
export APP_OBJECT_ID="$(jq -r .id .local/application.json)"
export API_CLIENT_ID="$(jq -r .appId .local/application.json)"
jq -n --arg uri "api://$API_CLIENT_ID" '{identifierUris:[$uri]}' > .local/identifier-uri.json
az rest --method patch --url "https://graph.microsoft.com/v1.0/applications/$APP_OBJECT_ID" \
--body @.local/identifier-uri.json
jq -n --arg id "$API_CLIENT_ID" '{appId:$id,appRoleAssignmentRequired:true}' > .local/sp-request.json
az rest --method post --url https://graph.microsoft.com/v1.0/servicePrincipals \
--body @.local/sp-request.json > .local/service-principal.json
export API_SP_ID="$(jq -r .id .local/service-principal.json)"
jq --arg client "$API_CLIENT_ID" --arg sp "$API_SP_ID" --arg role "$ROLE_ID" \
'. + {apiClientId:$client,apiServicePrincipalId:$sp,roleId:$role}' .local/context.json > .local/context.next.json
mv .local/context.next.json .local/context.json
node scripts/config.mjs prepare .local/context.json .local/prepare
Leave SERVICE_TREE_REFERENCE empty unless your tenant requires one.
Allow only the namespace sender
for body in trigger-grant negative-grant; do
az rest --method post --url "https://graph.microsoft.com/v1.0/servicePrincipals/$API_SP_ID/appRoleAssignedTo" \
--body "@.local/prepare/$body.json"
done
export APP_ID="$(jq -r .appResourceId .local/context.json)"
export NS_ID="$(jq -r .namespaceResourceId .local/context.json)"
export APP_URL="https://management.azure.com$APP_ID?api-version=2026-09-01-preview"
export NS_URL="https://management.azure.com$NS_ID"
az rest --method put --url "https://management.azure.com$APP_ID/authConfigs/default?api-version=2026-09-01-preview" \
--body @.local/prepare/auth-policy.json
az rest --method get --url "https://management.azure.com$APP_ID/authConfigs/default?api-version=2026-09-01-preview" \
> .local/auth-readback.json
In .local/auth-readback.json, confirm authentication is required,
entraId.state is Enabled, entraId.customerApplication.allowedAudiences
contains only the API client GUID, entraId.allowedTenantIds contains only
the selected tenant, and entraId.allowedObjectIds contains only the sender's
principal/object ID. These fields are under properties; do not substitute
an identity client ID for its principal/object ID.
Create the Outlook connection
export CONN_URL="$NS_URL/connections/outlook-test?api-version=2026-05-01-preview"
az rest --method put --url "$CONN_URL" --body @.local/prepare/connection.json
for kind in app trigger; do
principal="$(jq -r ".${kind}Identity.principalId" .local/context.json)"
az rest --method put --url "$NS_URL/connections/outlook-test/accessPolicies/$principal?api-version=2026-05-01-preview" \
--body "@.local/prepare/$kind-policy.json"
done
az rest --method get --url "$CONN_URL" \
--query '{connectionRuntimeUrl:properties.connectionRuntimeUrl}' > .local/connection.json
jq --slurpfile auth .local/auth-readback.json --slurpfile conn .local/connection.json \
'. + {appOrigin:($auth[0].properties.entraCallbackUrl|split("/.auth/login/aad/callback")[0]),
entraSetup:$auth[0].properties.entraSetup,connectionRuntimeUrl:$conn[0].connectionRuntimeUrl}' \
.local/context.json > .local/context.next.json
mv .local/context.next.json .local/context.json
node scripts/config.mjs runtime .local/context.json .local/runtime
On the existing app's Variables page, save
CONNECTOR_IDENTITY_CLIENT_ID_ENV=Identity_id_bld_app_<run>_ClientId and the
test prefix from the generated file. The selector names the app UAMI's
runtime-generated client-ID output; it is not a client ID or token stored in
Variables. Remove legacy AZURE_CLIENT_ID and manual runtime-URL entries
without deploying. Keep unrelated app variables unchanged.
Then save the generated named connection while preserving other connections:
az rest --method patch --url "https://graph.microsoft.com/v1.0/applications/$APP_OBJECT_ID" \
--body @.local/runtime/redirect.json
az rest --method post --url "https://graph.microsoft.com/v1.0/applications/$APP_OBJECT_ID/federatedIdentityCredentials" \
--body @.local/runtime/federation.json
az rest --method get --url "$APP_URL" > .local/current-app.json
APP_ETAG="$(jq -er .etag .local/current-app.json)"
jq --slurpfile desired .local/runtime/variables.json '
{properties:{versionConfiguration:{connections:
((.properties.versionConfiguration.connections // [] | map(select((.name | ascii_downcase) != "outlook")))
+ $desired[0].properties.versionConfiguration.connections)
}}}
' .local/current-app.json > .local/connection-update.json
az rest --method patch --url "$APP_URL" --headers "If-Match=$APP_ETAG" \
--body @.local/connection-update.json
The connection uses profile connectorNamespaceConnection, the existing
outlook-test resource, its HTTPS runtime URL mapped to
OFFICE365_CONNECTION_RUNTIME_URL, and the already assigned app UAMI.
Connections does not create that external resource, collect mailbox consent
or configure its access policy/trigger. On 412, refresh and reconcile;
do not overwrite a concurrent edit. Ordinary app GET does not supply
manual variable values for a replacement list.
4. Connect your fork and deploy
In Portal, open the existing app bld-connectors-<run>.
- In Authentication, verify required Entra authentication and the exact sender rule; in Identity, the app identity.
- In Architecture, open the
outlookconnection and verify its selected app UAMI and runtime-URL mapping. In Variables, verify only the generated identity-output selector andTEST_SUBJECT_PREFIX, with no old global client ID. - Open Settings → Source Control, authorize GitHub App access to your fork, select the branch and root, and save without deploying. Then open Settings → Deployment Settings and turn Automatic deployments off for this walkthrough.
- Deploy explicitly, wait for success, and verify the active version and revision in Versions.
Keep replicas at 0–2 and preserve idle timeout. The creation template owns scaling;
do not apply an older generated scaling.json through app PATCH.
The deployed catalog supports named configuration, but this sample's actual
mailbox operation must still be qualified for the selected revision.
Use the Builder CLI procedure with a release that includes app connections, or the guarded Azure CLI/ARM writes above.
Use the typed connector-namespace command with the exact outlook connection resource and selected UAMI.
Wait for propagationPending: false and matching revision / appliedRevision:
az rest --method get --url "https://management.azure.com$APP_ID/authConfigs/default?api-version=2026-09-01-preview"
5. Verify access and connect Outlook
Check callback authentication
export ORIGIN="$(jq -r .appOrigin .local/context.json)"
curl -i -X POST -H 'Accept: application/json' "$ORIGIN/api/webhook"
curl -i -X POST -H 'Accept: application/json' -H 'Authorization: invalid' "$ORIGIN/api/webhook"
curl -i -X POST -H 'Accept: application/json' -H 'X-MS-CLIENT-PRINCIPAL-ID: spoofed' "$ORIGIN/api/webhook"
az rest --method put --url "$NS_URL/triggerConfigs/auth-control?api-version=2026-05-01-preview" \
--body @.local/runtime/control-negative.json
node scripts/run-trigger.mjs .local/context.json control-negative
node scripts/run-trigger.mjs .local/context.json control-wrong-audience
node scripts/run-trigger.mjs .local/context.json control-allowed
| Check | Expected result |
|---|---|
| Three direct POSTs | 401, not a sign-in redirect |
| Valid-role wrong principal | 403; a 401 does not prove sender authorization |
| Wrong token audience | 401 |
| Allowed sender | 200 with received 0 / flagged 0 |
Don't connect a mailbox until all checks pass. The runner disables each control afterward; confirm after an interruption.
Sign in to the test mailbox
The mailbox owner approves consent in their native browser (connection policies don't limit OAuth permissions to flagging):
python3 - <<'PY'
import json, os, subprocess, webbrowser
base = os.environ["NS_URL"] + "/connections/outlook-test"
api = "?api-version=2026-05-01-preview"
creator = json.loads(subprocess.check_output(
["az","rest","--method","get","--url",base+api,
"--query","properties.createdBy","-o","json"], text=True))
body = {"parameters":[{"objectId":creator["objectId"],"tenantId":creator["tenantId"],
"redirectUrl":"https://microsoft.com","parameterName":"token"}]}
link = subprocess.check_output(
["az","rest","--method","post","--url",base+"/listConsentLinks"+api,
"--body",json.dumps(body),"--query","value[0].link","-o","tsv"], text=True).strip()
if not webbrowser.open(link):
raise SystemExit("Browser did not open. Stop; do not publish or regenerate the consent link.")
PY
az rest --method get --url "$CONN_URL" \
--query '{status:properties.overallStatus,user:properties.authenticatedUser}'
Confirm Connected and the intended user; if already connected, skip consent.
6. Verify the Outlook event
Start a five-minute test window:
printf 'Matching subject: [builder-connector-%s] validation\nControl subject: connector control %s\n' "$RUN" "$RUN"
az rest --method put --url "$NS_URL/triggerConfigs/mail-test?api-version=2026-05-01-preview" \
--body @.local/runtime/mail-trigger.json
node scripts/run-trigger.mjs .local/context.json mail-trigger 300
Wait for Enabled in the terminal, then from the approved mailbox send one unflagged harmless message without attachments to that same mailbox for each printed subject. Don't resend when the outcome is unknown.
Expect callback 200 with received 1 / flagged 1, the matching email flagged, and the control unchanged (retries can repeat a flag; this isn't exactly-once). The runner disables the trigger afterward; confirm Disabled after interruptions, and inspect the existing run rather than sending more messages. Stop at 30 minutes enabled, twenty callbacks, ten flag attempts, or two test messages, whichever comes first.
Clean up resources
Delete only what you created. Confirm the resource group contains only the resources created above. Do not delete the shared Office365 enterprise application or any pre-existing resource. Preserve both synthetic messages unless their owner approves a change. Don't create a missing trigger during cleanup. Inspect resources and trigger states first:
az resource list --subscription "$SUBSCRIPTION_ID" --resource-group "$RG" \
--query '[].{name:name,type:type}'
az rest --method get --url "$NS_URL/triggerConfigs?api-version=2026-05-01-preview" \
--query 'value[].{name:name,state:properties.state}'
Both mail-test and auth-control must be Disabled. If either is Enabled, run only its PUT below, then read back the states:
az rest --method put --url "$NS_URL/triggerConfigs/mail-test?api-version=2026-05-01-preview" \
--body @.local/runtime/mail-trigger.json
az rest --method put --url "$NS_URL/triggerConfigs/auth-control?api-version=2026-05-01-preview" \
--body @.local/runtime/control-negative.json
az rest --method get --url "$NS_URL/triggerConfigs?api-version=2026-05-01-preview" \
--query 'value[].{name:name,state:properties.state}'
Delete the triggers, policies, connection, and group, then the receiver service principal and registration (group deletion doesn't remove directory objects):
for name in mail-test auth-control; do
az rest --method delete --url "$NS_URL/triggerConfigs/$name?api-version=2026-05-01-preview"
done
for kind in app trigger; do
principal="$(jq -r ".${kind}Identity.principalId" .local/context.json)"
az rest --method delete --url "$NS_URL/connections/outlook-test/accessPolicies/$principal?api-version=2026-05-01-preview"
done
az rest --method delete --url "$CONN_URL"
az group delete --subscription "$SUBSCRIPTION_ID" --name "$RG" --yes
az rest --method delete --url "https://graph.microsoft.com/v1.0/servicePrincipals/$API_SP_ID"
az rest --method delete --url "https://graph.microsoft.com/v1.0/applications/$APP_OBJECT_ID"
Verify deletion before removing .local/:
az group exists --subscription "$SUBSCRIPTION_ID" --name "$RG"
az rest --method get --url "https://graph.microsoft.com/v1.0/applications?\$filter=appId%20eq%20%27$API_CLIENT_ID%27&\$select=id" --query value
az rest --method get --url "https://graph.microsoft.com/v1.0/servicePrincipals?\$filter=appId%20eq%20%27$API_CLIENT_ID%27&\$select=id" --query value
for kind in app trigger negative; do
principal="$(jq -r ".${kind}Identity.principalId" .local/context.json)"
az rest --method get --url "https://graph.microsoft.com/v1.0/servicePrincipals?\$filter=id%20eq%20%27$principal%27&\$select=id" --query value
done
Expect false, then five empty arrays; if propagating, wait and repeat.