Auto-Granting Shared Mailbox Access With an AI Intent Bot
An Azure OpenAI intake bot parses shared mailbox requests, checks policy, grants Exchange Online access and verifies it before the ticket is resolved.

This playbook covers
Table of Contents
Table of contents
#The Old Way vs the New Way
A finance analyst needs Send As rights on the “AP-Invoices” shared mailbox before a supplier payment run. The old way starts with an email to the helpdesk alias, which sits in a shared queue until an L1 technician picks it up, cannot verify management approval unaided, and forwards it to L2. L2 waits for a manager to reply “approved” in an email thread, then runs a single Exchange OnlineThe KBY LexiconExchange OnlineExchange Online is Microsoft's cloud-hosted email, calendar and contacts service, delivered through Microsoft 365 as hosted mailbox infrastructure. cmdlet that takes ninety seconds to execute. The ticket itself, from submission to closure, routinely spans two to four business days and consumes three separate humans for work that is genuinely five minutes of typing once approval exists.
The new way removes every human touchpoint except the one that actually needs judgement: the approval decision. A Teams-based AI intake bot, built on Azure OpenAI function calling, reads the natural-language request, extracts the mailbox name and permission type, checks the request against a self-service policy table, and either auto-grants low-risk requests or routes an adaptive card approval to the correct manager. Once approved, an Azure Automation runbook executes the Exchange Online permission grant using an app-only certificate identity, then closes the ticket and posts the evidence back into the conversation. No technician opens a ticket queue for this category of request again unless the automation itself fails.
#Prerequisites and Permissions
Get the identity and scoping decisions right before touching code. This automation grants mailbox permissions, so it must run with the narrowest possible Exchange Online role and must never inherit Global Administrator rights.
- An Azure AD app registration with an uploaded certificate (no client secrets) for app-only Exchange Online authentication.
- An Exchange Online custom management role group, scoped by a management scope OU or recipient filter, granting only the specific role required for permission changes.
- An Azure OpenAI resource (GPT-4o or later) with function calling enabled, deployed in a region matching your data residency requirement.
- A Teams bot registration (Azure Bot Service) using the Microsoft Bot Framework SDK, or an equivalent Slack app if your organisation uses Slack.
- An approval flow tied to the requester’s manager, pulled from the Azure AD manager attribute, delivered as a Teams adaptive card with a callback action.
- A pre-approved self-service policy table (a SharePoint list, Dataverse table, or JSONThe KBY LexiconJSONJSON (JavaScript Object Notation) is a lightweight, text-based data-interchange format built from key-value pairs and ordered lists, defined by RFC 8259. config) listing mailboxes eligible for auto-grant without manager sign-off, such as shared calendars or low-sensitivity distribution mailboxes.
- Write access to your ticketing system’s RESTThe KBY LexiconRESTREST defines resource-oriented, stateless APIs built on a uniform interface; understanding its constraints clarifies scaling, caching and safe validation of state-changing calls. API (ServiceNow Table API or equivalent) to log and auto-close the resulting ticket record.
Configuring this pipeline needs an Exchange role group that includes the Role Management role (for example Organization Management) to create the management scope, role group and service principal, plus Application Administrator for the app registration, not Global Administrator; Exchange Recipient Administrator alone cannot create role groups or scopes. Day-to-day operation needs neither. Test scope for the pilot should be five non-critical shared mailboxes with no financial or regulatory sensitivity, and the blast radius is limited to mailbox permission entries, not mailbox content, licensing, or forwarding rules.

#Implementation Steps
- Register the automation identity. Action: create an Azure AD app registration, upload a certificate (no secret), register the app in Exchange Online as a service principal, and make that service principal (not a user account) the member of a custom role group scoped to the pilot mailboxes only. Run the commands below as an administrator in a role group that includes the Role Management role (for example Organization Management). Rather than assuming which built-in role holds each cmdlet, list the roles that contain Add-RecipientPermission, Add-MailboxPermission and Set-Mailbox with Get-ManagementRole -Cmdlet and put those in the role group; for production, derive a custom role (New-ManagementRole -Parent) limited to the cmdlets the runbook uses, and test each cmdlet against a pilot mailbox before go-live. Expected result: the app can authenticate non-interactively and change permissions only on the five pilot mailboxes; before any live grant, confirm that a grant on a test mailbox outside the scope is refused. Evidence: the Get-ManagementRoleAssignment output for the new role group and the refused attempt, stored in the change record.
1# Needs an admin in a role group with the Role Management role, for example Organization Management 2Connect-ExchangeOnline -UserPrincipalName "admin@kbytech.onmicrosoft.com" 3 4# Tag the five pilot mailboxes with CustomAttribute1 = MailboxAutomationPilot first 5New-ManagementScope -Name "PilotMailboxes" -RecipientRestrictionFilter "CustomAttribute1 -eq 'MailboxAutomationPilot'" 6 7# Register the app as an Exchange service principal (AppId and the enterprise application's object ID) 8New-ServicePrincipal -AppId "11111111-2222-3333-4444-555555555555" -ObjectId "<enterprise-app-object-id>" -DisplayName "SharedMailboxAutomation" 9 10# List the roles that contain each cmdlet the runbook calls, and use those names in -Roles 11Get-ManagementRole -Cmdlet Add-RecipientPermission 12Get-ManagementRole -Cmdlet Add-MailboxPermission 13Get-ManagementRole -Cmdlet Set-Mailbox 14 15New-RoleGroup -Name "SharedMailboxAutomation-Pilot" -Roles "<role-from-output>","<role-from-output>" -CustomRecipientWriteScope "PilotMailboxes" 16Add-RoleGroupMember -Identity "SharedMailboxAutomation-Pilot" -Member (Get-ServicePrincipal -Identity "SharedMailboxAutomation").Identity 17 18# Confirm the roles and the write scope the service principal now holds 19Get-ManagementRoleAssignment -RoleAssignee "SharedMailboxAutomation-Pilot" | Format-Table Role,CustomRecipientWriteScopeExpected output:
1Role CustomRecipientWriteScope 2---- ------------------------- 3<role-from-output> PilotMailboxes - Define the function-calling schema for the AI intake bot. Action: describe the “grant_mailbox_access” function to Azure OpenAI so the model returns structured arguments instead of free text. Expected result: a message like “can I get Send As on AP-Invoices” resolves to a JSON object with mailbox, permission_type and requester fields. Evidence: log the raw model completion and the parsed arguments for every request in Application Insights.
1{ 2 "type": "function", 3 "function": { 4 "name": "grant_mailbox_access", 5 "description": "Request permission on a shared mailbox for the current Teams user.", 6 "parameters": { 7 "type": "object", 8 "properties": { 9 "mailbox": { 10 "type": "string", 11 "description": "The shared mailbox display name or primary SMTP address." 12 }, 13 "permission_type": { 14 "type": "string", 15 "enum": ["FullAccess", "SendAs", "SendOnBehalf"] 16 }, 17 "justification": { 18 "type": "string", 19 "description": "One sentence business reason supplied by the requester." 20 } 21 }, 22 "required": ["mailbox", "permission_type", "justification"] 23 } 24 } 25} - Validate the request against the self-service policy table. Action: the bot’s backend checks whether the requested mailbox is tagged auto-approve or requires manager sign-off, and confirms the requester is a licensed user in good standing. Expected result: low-risk mailboxes skip straight to provisioning; everything else generates an approval card. Evidence: the policy lookup result and decision reason are written to the automation log before any Exchange call is made.
1def resolve_policy(mailbox, requester_upn, policy_table): 2 entry = policy_table.get(mailbox.lower()) 3 if entry is None: 4 return {"decision": "escalate", "reason": "mailbox not in policy table"} 5 if entry["auto_approve"] and is_active_user(requester_upn): 6 return {"decision": "auto_approve", "reason": "pre-approved low-risk mailbox"} 7 return {"decision": "manager_approval", "manager": get_manager(requester_upn)} - Send the adaptive card approval when required. Action: for anything outside the auto-approve list, post an adaptive card to the requester’s manager with Approve and Reject actions. Expected result: the manager receives a native Teams card within seconds, and the response is captured via the bot’s action callback. Evidence: store the manager’s decision, timestamp and Teams message ID against the request record.
1{ 2 "type": "AdaptiveCard", 3 "version": "1.5", 4 "body": [ 5 { 6 "type": "TextBlock", 7 "text": "Approval needed: SendAs on AP-Invoices for j.morgan@kbytech.com", 8 "wrap": true, 9 "weight": "Bolder" 10 }, 11 { 12 "type": "TextBlock", 13 "text": "Justification: Processing supplier payment run.", 14 "wrap": true 15 } 16 ], 17 "actions": [ 18 { "type": "Action.Submit", "title": "Approve", "data": { "decision": "approve" } }, 19 { "type": "Action.Submit", "title": "Reject", "data": { "decision": "reject" } } 20 ] 21} - Provision the permission with an Azure Automation runbook. Action: once the decision is auto_approve or manager approved, trigger a runbook via webhook that runs Add-MailboxPermission or Add-RecipientPermission depending on permission_type. Because the inputs come from a model and a requester, the runbook itself refuses to act unless the mailbox carries the pilot tag, the requester resolves to a user mailbox, and the day’s grant count is under a hard cap held in an Automation variable created before first use; a refusal fails the job, which triggers the escalation conditions below. Expected result: the permission entry exists when the runbook’s confirmation query runs. A new permission can take a while to take effect in Outlook, so poll its state before closing the ticket. Evidence: the runbook job output and the confirmation query for the relevant permission type are attached to the ticket record.
1param( 2 [Parameter(Mandatory = $true)][string]$Mailbox, 3 [Parameter(Mandatory = $true)][string]$Requester, 4 [Parameter(Mandatory = $true)][ValidateSet("FullAccess", "SendAs", "SendOnBehalf")][string]$PermissionType 5) 6 7Connect-ExchangeOnline -CertificateThumbprint $env:AUTOMATION_CERT_THUMBPRINT -AppId $env:AUTOMATION_APP_ID -Organization "kbytech.onmicrosoft.com" 8 9# Guards before any change: pilot mailbox, resolvable requester, hard daily cap (Automation variable GrantCounter) 10$Target = Get-Mailbox -Identity $Mailbox -ErrorAction Stop 11if ($Target.CustomAttribute1 -ne 'MailboxAutomationPilot') { throw "$Mailbox is not an approved pilot mailbox" } 12$User = Get-Recipient -Identity $Requester -ErrorAction Stop 13if ($User.RecipientTypeDetails -ne 'UserMailbox') { throw "$Requester is not a user mailbox" } 14$Today = (Get-Date).ToString('yyyy-MM-dd') 15$Counter = Get-AutomationVariable -Name 'GrantCounter' 16$Count = if ($Counter -like "$Today|*") { [int]$Counter.Split('|')[1] } else { 0 } 17if ($Count -ge 10) { throw 'Daily cap of 10 automated grants reached; route to L2' } 18Set-AutomationVariable -Name 'GrantCounter' -Value "$Today|$($Count + 1)" 19$Mailbox = $Target.PrimarySmtpAddress.ToString() 20$Requester = $User.PrimarySmtpAddress.ToString() 21 22switch ($PermissionType) { 23 "FullAccess" { Add-MailboxPermission -Identity $Mailbox -User $Requester -AccessRights FullAccess -AutoMapping:$false } 24 "SendAs" { Add-RecipientPermission -Identity $Mailbox -Trustee $Requester -AccessRights SendAs -Confirm:$false } 25 "SendOnBehalf" { Set-Mailbox -Identity $Mailbox -GrantSendOnBehalfTo @{Add=$Requester} } 26} 27 28# Confirm with the cmdlet that matches the permission type 29switch ($PermissionType) { 30 "FullAccess" { Get-MailboxPermission -Identity $Mailbox -User $Requester | Format-List } 31 "SendAs" { Get-RecipientPermission -Identity $Mailbox -Trustee $Requester | Format-List } 32 "SendOnBehalf" { Get-Mailbox -Identity $Mailbox | Select-Object -ExpandProperty GrantSendOnBehalfTo } 33}Expected output for a Send As grant (from Get-RecipientPermission):
1Identity : AP-Invoices 2Trustee : j.morgan@kbytech.com 3AccessControlType : Allow 4AccessRights : {SendAs} 5IsInherited : False - Close the loop with the ticketing system. Action: only after the confirmation query shows the permission in place, the runbook posts a completion webhook to ServiceNow’s Table API, creating and resolving an incident record with the full audit trail attached (if the confirmation fails, it creates the incident unresolved and routes it to L2), so reporting still shows a ticket existed even though no human worked it. Expected result: a closed, auto-resolved incident appears in the queue with resolution notes, and the requester receives a Teams confirmation message. Evidence: the HTTP 201 response from ServiceNow and the ticket number returned in the payload.
1{ 2 "short_description": "Shared mailbox access - AP-Invoices - SendAs", 3 "category": "Access Request", 4 "state": "Resolved", 5 "close_code": "Solved (Automated)", 6 "close_notes": "Granted via AI intake bot. Approval path: manager approval by m.chen@kbytech.com (or: auto-approved per policy table). Permission verified. Runbook job ID rb-20482.", 7 "u_automation_source": "TeamsIntentBot-v2", 8 "caller_id": "j.morgan@kbytech.com" 9} - Pilot for two weeks before widening scope. Action: run the full flow against only the five pilot mailboxes for at least ten business days, comparing auto-resolution against a shadow queue where L2 still manually reviews the same requests without acting. Expected result: zero mismatches between the automation’s decision and what the shadow reviewer would have done. Evidence: a side-by-side comparison spreadsheet exported from the automation log and the shadow queue.
#Verification and Expected Evidence
Before declaring this live for a wider mailbox set, confirm three things independently of the automation’s own logs. First, run Get-MailboxPermission and Get-RecipientPermission against each pilot mailbox and diff the result against the automation’s own record of what it granted; they must match exactly. Second, pull the Microsoft 365 unified audit log for the “Add-MailboxPermission” and “Add-RecipientPermission” operations and parse each entry’s AuditData to confirm the grant came from the automation’s app registration, not an interactive admin session. The UserIds column alone does not show this, and the field holding the application ID (such as AppId or ClientAppId) and the exact operation names can differ, so check both against a known test grant in your tenant first. Third, confirm every ticket created by the webhook carries the u_automation_source field, so reporting can separate AI-resolved tickets from manually worked ones without guesswork.
1Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) -Operations "Add-MailboxPermission","Add-RecipientPermission" -ResultSize 50 |
2 ForEach-Object { $_.AuditData | ConvertFrom-Json } |
3 Select-Object CreationTime, UserId, Operation, AppId, ClientAppId, ObjectId#Rollback
Every grant this pipeline makes can be reversed with the matching cmdlet, which is part of why it is reasonable to automate. If a permission was granted in error, or the policy table was misconfigured and something was auto-approved that should not have been, first check the automation log and current permissions so you do not remove a legitimate earlier grant, then run only the command below that matches the grant made in error, and stop the automation as described next.
1# FullAccess
2Remove-MailboxPermission -Identity "AP-Invoices" -User "j.morgan@kbytech.com" -AccessRights FullAccess
3# SendAs
4Remove-RecipientPermission -Identity "AP-Invoices" -Trustee "j.morgan@kbytech.com" -AccessRights SendAs
5# SendOnBehalf
6Set-Mailbox -Identity "AP-Invoices" -GrantSendOnBehalfTo @{Remove="j.morgan@kbytech.com"}If the fault is in the policy table itself rather than a single grant, disable the runbook’s webhook trigger in Azure Automation, set the bot’s fallback response to “Your request has been forwarded to a technician” and route all incoming requests to the human L2 queue until the policy entry is corrected and retested against the pilot mailboxes.
#Failure and Escalation Conditions
This automation should escalate to a human technician automatically, not silently retry, under any of these conditions:

- The Azure OpenAI function call returns a mailbox name that does not resolve to an existing distribution or shared mailbox object after a Get-Recipient lookup.
- The manager approval card receives no response within four business hours, at which point the request routes to the requester’s manager’s manager and pages the on-call L2 technician.
- The Azure Automation runbook job status returns Failed or Suspended, which should fire a Log Analytics alert to the messaging team’s on-call channel within five minutes.
- The certificate used for app-only authentication is within thirty days of expiry, flagged by a scheduled Azure Automation health check, not discovered when a grant silently fails.
- Any request targets a mailbox tagged as regulated (legal hold, litigation, or finance-controlled) in the policy table; these must always route to manual review regardless of auto-approve settings.
#Measuring Ticket Deflection
Deflection here is not “fewer emails,” it is a measurable drop in average handling time and a rising share of access-request tickets closed with zero human touch. Track these numbers weekly for the first quarter after go-live:
- Percentage of “Shared Mailbox Access” category tickets closed with close_code “Solved (Automated)” versus manually worked.
- Median time from request to resolution, split by auto-approved versus manager-approved paths.
- Escalation rate: the proportion of automated requests that hit one of the failure conditions above and required a human.
- False-grant rate from the verification audit: any permission that should not have been approved, caught within seven days.
1SELECT
2 DATE_TRUNC('week', opened_at) AS week,
3 COUNT(*) AS total_requests,
4 SUM(CASE WHEN close_code = 'Solved (Automated)' THEN 1 ELSE 0 END) AS auto_resolved,
5 ROUND(100.0 * SUM(CASE WHEN close_code = 'Solved (Automated)' THEN 1 ELSE 0 END) / COUNT(*), 1) AS deflection_pct
6FROM incidents
7WHERE category = 'Shared Mailbox Access'
8GROUP BY 1
9ORDER BY 1;A pilot running against five mailboxes for two weeks with zero mismatches and a four-hour median resolution time on the manager-approval path (down from two to four days) is a reasonable bar to clear before widening the policy table. Expand in small increments of five to ten mailboxes, each with a signed-off go/no-go decision, re-running the verification audit after each batch rather than switching every mailbox on at once. Before widening, review the runbook’s daily cap against real request volumes (anything over it fails and routes to L2), and document the stop procedure: disabling the runbook’s webhook halts all automated grants immediately.
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
About this page
Read-only scripts
- Windows devices with no BitLocker recovery key in Entra IDMicrosoft Entra ID, Windows
- Intune devices that haven't synced in N daysMicrosoft Intune
- Mailboxes forwarding to external addressesExchange Online
- BitLocker status of every volume on this PCWindows
Upcoming deadlines
- Intune moves to macOS 15 and laterQ4 2026
- SAP SuccessFactors provisioning: move from basic auth to workload identityNovember 2026
- Intune November release: JIT registration reminder at APNs renewal and automatic JIT for eligible tenantsNovember 2026
Explore KBY
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
SubscribeRelated articles
Security & Compliance
Engineer Out Standing Local Admin Requests With JIT Elevation
Standing local admin rights fail audits; this JIT elevation automation grants time-bound access and auto-revokes it, closing the ticket permanently.
Enterprise IT Management
Exchange Online 550 5.7.708 Access Denied: Fixing Blocked Mail Flow
How to diagnose Exchange Online 550 5.7.708: find the real source IP, check reputation and connectors, validate recovery and escalate to Microsoft with evidence.
Outages
Microsoft 365 Outage, November 2026: What Went Wrong, How Microsoft Can Fix It, and What to Do Now
Microsoft says a network capacity upgrade caused the global Microsoft 365 outage that hit Outlook, Exchange Online and Teams from Thursday 12 November, and reports broad recovery. What happened, what Microsoft has said, our view, and what IT teams should do now.
Learn More About KBY
About KBY
Learn about our mission, how our content is produced, and how we handle corrections.
Why Trust KBY
How KBY content is produced, what is checked automatically, and how errors are corrected.
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
Operate smarter, with fewer recurring tickets.
Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.
Comments
Add a thoughtful note on Auto-Granting Shared Mailbox Access With an AI Intent Bot. Comments are checked for spam and held for moderation before appearing.