Hive BDC: e-invoicing for Dynamics AX and D365 F&O
Balsoft Data Connector: send and receive e-invoices (XRechnung, ZUGFeRD) for Microsoft Dynamics 365 F&O, AX 2012 and AX 2009.
Installation · one day
- Download the setup (130 MB, signed by Balsoft)
- Install service and dashboard
- Dynamics module installed by Balsoft
- Send a test document as XRechnung
- Go-live
D365 F&O · AX 2012 · AX 2009
Outgoing and incoming invoices in one flow
Hive BDC turns a posted sales invoice into a German e-invoice in XRechnung or ZUGFeRD format. Order confirmations, quotations, collection letters, purchase orders and payment advices go out as the PDF your ERP prints. Each document can be mailed to the recipient and filed in SharePoint, ShareFlex, DocuWare or the DMS you already use. In the other direction Hive BDC takes your vendors' e-invoices from a mailbox, a folder or your DMS (for example SharePoint) and over Peppol, reads XRechnung and ZUGFeRD in CII and UBL, checks them against EN 16931 and compares the totals. Hive BDC then creates a pending vendor invoice, a purchase order invoice or an invoice journal in Dynamics.
A Windows service does the work in the background, a dashboard shows what went out and what came in and holds the settings. On the ERP side, Hive BDC includes a module for Dynamics, which Balsoft installs for you.
Supported systems
Standards
How Hive BDC works
Two directions, one product. Outgoing invoices leave Dynamics as XRechnung or ZUGFeRD, incoming e-invoices land in Dynamics as vendor invoices. Both run as batch jobs, nobody has to touch a file.
Accounts receivable (AR): how an e-invoice goes out of Dynamics AX 2009, AX 2012 and D365 F&O on-premises (LBD)
From the posted invoice in Dynamics to the customer's mailbox and your archive, without anyone touching it.
The invoice is posted in Dynamics
Accounts payable (AP): how an e-invoice gets into Dynamics
From your vendor's e-invoice in the mailbox, over Peppol, in a folder or in your DMS (for example SharePoint) to the vendor invoice in AX 2009, AX 2012 or D365 F&O, without typing anything in.
The vendor's e-invoice arrives
What it does
Accounts receivable (AR): XRechnung and ZUGFeRD
Sales invoices become e-invoices according to EN 16931, checked before they leave, including credit notes, cash discounts and settlement house data.
Accounts payable (AP)
Your vendors' e-invoices arrive by mail, folder, DMS (for example SharePoint) or Peppol. Hive BDC reads XRechnung and ZUGFeRD (CII and UBL), checks them and creates a pending vendor invoice, a purchase order invoice or an invoice journal.
PDF documents
Order confirmations, quotations, collection letters, purchase orders and payment advices are sent as the PDF your ERP prints.
Smaller PDFs
With Compress PDF on, each PDF is made smaller once before it goes out: fonts keep only the letters used, and images placed above 300 ppi go to 200 ppi. Pages look the same. A ZUGFeRD invoice from AX 2009 went from 945 KB to 138 KB.
Mail through Microsoft 365
Recipient, subject and text come from the ERP. Documents are sent from your own mailbox and kept in its sent items.
SharePoint, DocuWare and other DMS
Documents go straight into a SharePoint library, also with ShareFlex, with metadata columns filled from the document. DocuWare, d.velop, ELO, M-Files, enaio, windream and other DMS read the finished files from the output folder (local, network share or a synced cloud folder) with their folder import or their own connector.
Runs on your servers
Document content never goes to Balsoft or another service, only to the recipients and the SharePoint site you set up.
Test systems stay internal
Documents from a test or development system go to your test recipients, never to a customer or vendor.
E-invoice formats
Which format a customer receives is set in the ERP, per invoice: XRechnung as XML, or ZUGFeRD as a PDF with the same XML inside. Both follow EN 16931 and are checked before they leave.
XRechnung
3.0.2For the public sector (with Leitweg-ID) and every recipient who processes XML.
- Format
- XML, UN/CEFACT CII syntax
- Standard
- EN 16931 with the German CIUS
- Specification ID
- urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0
- File
- One XML file per invoice
- Tested with
- KoSIT validator 1.6.3, configuration 2026-08-31 (XRechnung 3.0.2)
ZUGFeRD
2.5.2 / Factur-X 1.09.2For recipients who want a readable PDF and machine-readable data in one file.
- Format
- PDF/A-3b with the XML attached
- Profile
- XRECHNUNG: the same XRechnung 3.0.2 XML as on the left
- Inside the PDF
- xrechnung.xml, Factur-X XMP metadata, sRGB output intent, fonts embedded
- Source
- The invoice PDF your ERP prints
- Tested with
- Mustang 2.26 with the ZUGFeRD 2.5.2 rules and the PDF/A-3 check (veraPDF), KoSIT validator for the XML
What the e-invoice carries
- Invoices, credit notes and corrected invoices (type codes 380, 381 and 384)
- Leitweg-ID for public-sector buyers (BT-10)
- Order, contract, project, delivery note and tender references (BT-11 to BT-17)
- Cash discounts (Skonto), also in several stages, in the machine-readable XRechnung form
- VAT per rate and category, so 19 % and 7 % on one invoice
- Bank details, delivery date and remittance information
- Item numbers, GTIN and country of origin per line
- Settlement house identifiers, for example for Aktivbank
Every invoice runs through a check of the EN 16931 and XRechnung business rules before it is written. Each finding is logged with its official rule ID, for example BR-DE-15, so missing data can be fixed in the ERP.
All other documents (order confirmations, quotations, collection letters, purchase orders, payment advices) go out as the PDF your ERP prints.
Hive BDC follows new versions of both standards. XRechnung 4.0, based on the revised EN 16931, is expected in spring 2027; XRechnung 3.0.2 stays valid until at least 31 July 2027. Updates arrive through the dashboard.
E-invoicing by Dynamics version
Dynamics AX 2012
E-invoicing for Microsoft Dynamics AX 2012
German e-invoices from Microsoft Dynamics AX 2012 R3 without an upgrade: XRechnung 3.0.2 and ZUGFeRD 2.5.2, checked against EN 16931, sent by mail.
Learn moreDynamics AX 2009
E-invoicing for Microsoft Dynamics AX 2009
German e-invoices from Microsoft Dynamics AX 2009 without an upgrade: XRechnung 3.0.2 and ZUGFeRD 2.5.2, checked against EN 16931, built from AX PDFs.
Learn moreDynamics 365 F&O
E-invoicing for D365 F&O: Dynamics 365 Finance & Operations
E-invoicing from D365FO and Dynamics 365 F&O: XRechnung 3.0.2 and ZUGFeRD 2.5.2 with Hive BDC, checked against EN 16931, sent by mail, filed in your DMS.
Learn moreWorks with the DMS you have: SharePoint and ShareFlex directly; DocuWare, d.velop documents, ELO, M-Files, enaio, windream, SER Doxis, nscale, EASY archive, Laserfiche, OpenText and other document management systems through the output folder, which they read with their folder import or their own connector.
Licence and source code
Licence
EUR 10,000
per year, plus VAT
- Support and updates included
- Licence file valid for 12 months, a new one comes with each yearly invoice
- Installed from the dashboard, no restart needed
Source code
The complete source code of Hive BDC is public on GitHub. Your IT, auditors and partners can check exactly what runs on your server before you install it.
Source available, not open source: running, copying or changing the software needs a licence from Balsoft.
View source code on GitHubSystem requirements
What you need to install and use Hive BDC. Your Balsoft consultant goes through it with you and installs the ERP part.
Dynamics
- Dynamics 365 Finance & Supply Chain Management in the cloud.
- The Hive BDC module in the ERP, delivered and installed by Balsoft.
- A batch server that runs the Hive BDC export jobs.
Azure
- An Azure Service Bus namespace or a storage account in your Azure subscription; Dynamics 365 and Hive BDC exchange the documents through it.
- Balsoft sets up the connection; the credentials stay in your Key Vault.
Microsoft 365 (for sending by mail)
- Mail: an Entra ID app registration with Mail.Send and the sending mailbox. Balsoft provides a script that sets it up and limits it to that mailbox.
- HTTPS access from the server to login.microsoftonline.com and graph.microsoft.com.
Licence
- A licence file from Balsoft, bound to your Microsoft 365 tenant. It unlocks e-invoices, PDF documents and SharePoint.
- The dashboard warns before it expires. Documents are never lost: without a valid licence they wait in the export folder.
SharePoint or another DMSOptional
- Only when documents should also be filed. Hive BDC runs without it.
- SharePoint: an app registration with Sites.ReadWrite.All, or Sites.Selected on the target site.
- DocuWare, d.velop, ELO, M-Files and other DMS: Hive BDC writes the finished files to an output folder (local, network share or a cloud folder synced to the server), and the DMS reads them with its folder import or its own connector.
Server
- Windows Server 2016, 2019, 2022 or 2025, 64-bit, with Desktop Experience. Windows 10 or 11, 64-bit, for test systems.
- Nothing else to install: the Setup brings the .NET runtime it needs.
- About 250 MB for the program, plus space for documents and logs (kept 30 days).
- Local administrator rights for the installation. The service runs as LocalSystem, or as a domain account when the export folder is on a network share.
Dynamics
- Dynamics AX 2012 R3 or Dynamics AX 2009, also Dynamics 365 F&O on-premises.
- The Hive BDC module in the ERP, delivered and installed by Balsoft.
- A batch server that runs the Hive BDC export jobs.
Export folder
- A local folder or network share where the ERP writes the documents and Hive BDC picks them up.
- Read and write access for the ERP service account and the Hive BDC service account.
Microsoft 365 (for sending by mail)
- Mail: an Entra ID app registration with Mail.Send and the sending mailbox. Balsoft provides a script that sets it up and limits it to that mailbox.
- HTTPS access from the server to login.microsoftonline.com and graph.microsoft.com.
Licence
- A licence file from Balsoft, bound to your Microsoft 365 tenant. It unlocks e-invoices, PDF documents and SharePoint.
- The dashboard warns before it expires. Documents are never lost: without a valid licence they wait in the export folder.
SharePoint or another DMSOptional
- Only when documents should also be filed. Hive BDC runs without it.
- SharePoint: an app registration with Sites.ReadWrite.All, or Sites.Selected on the target site.
- DocuWare, d.velop, ELO, M-Files and other DMS: Hive BDC writes the finished files to an output folder (local, network share or a cloud folder synced to the server), and the DMS reads them with its folder import or its own connector.
Downloads
Version 1.15.1, released 27 November 2026, about 130 MB, Windows x64
Hive BDC Setup
Version 1.15.1, released 27 November 2026, about 130 MB, Windows x64
One file with everything you install: the Windows service and its dashboard. The file is signed by Balsoft GmbH; Windows shows Balsoft GmbH as the publisher. Installed systems update themselves from the dashboard.
Download Setup 1.15.1SHA-256 checksum:d059b0a5ce15a657a9b4b5537ac03cf7496b685b950e2f9d896d761393320800
Installation and user guides
PDF, in English. The German version is on the German page.
- Microsoft Dynamics AX 2012PDF, 5.8 MB
- Dynamics 365 Finance and OperationsComing soon
- Microsoft Dynamics AX 2009PDF, 6.3 MB
Microsoft 365 setup for mail and SharePoint
For your IT administrator. Only needed if Hive BDC mails documents or files them in SharePoint.
Setup guide
Hive BDC signs in to Microsoft 365 with two app registrations in your tenant: one may send as a single mailbox, the other may write only to the SharePoint sites you name. Two PowerShell scripts set them up in Azure Cloud Shell in a few minutes. They ask before changing anything and never create or store a secret. The guide walks through every step.
Run it in Azure Cloud Shell
Each app is set up in two steps in Azure Cloud Shell (PowerShell) of your tenant: first the app registration, then its permissions. The steps can be done by different administrators. Each script shows the tenant and asks before it changes anything; add -WhatIf for a dry run.
The source of both scripts is also public in the Hive BDC repository on GitHub.
1Create the app registration
Creates "Hive BDC Mail" without any permission and prints its client ID. Needs Application Administrator.
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/New-HiveBDCMailApp.ps1 -OutFile New-HiveBDCMailApp.ps1./New-HiveBDCMailApp.ps1<#.SYNOPSIS Step 1 of 2 for Mail: creates the app registration "Hive BDC Mail", without any permission..DESCRIPTION Run in Azure Cloud Shell (PowerShell). It shows the tenant and asks first, skips the app if it already exists, creates its service principal, and prints the IDs plus the command for step 2, Grant-HiveBDCMailAccess.ps1, which assigns the right to send as one mailbox. Role: Application Developer or Application Administrator. No client secret is created; the script prints how. -WhatIf shows the plan only..EXAMPLE ./New-HiveBDCMailApp.ps1#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param( [ValidateLength(3, 120)] [string] $AppName = 'Hive BDC Mail', [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')] [string] $TenantId, # Do not ask before changing the tenant. [switch] $Force)$ErrorActionPreference = 'Stop'function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host " [ok] $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host " [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host " $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az { $output = & az @args --only-show-errors --output json if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." } $text = ($output | Out-String).Trim() if (-not $text) { return } $parsed = $text | ConvertFrom-Json return $parsed # return, not the pipeline, so a JSON array arrives as its items}function Get-AzCliAccount { $ErrorActionPreference = 'Continue' # 'not signed in' arrives on stderr $text = (& az account show --output json 2>$null | Out-String).Trim() if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/2 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) { throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) { $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none') if ($TenantId) { $login += @('--tenant', $TenantId) } if ($useDeviceCode) { $login += '--use-device-code' } & az @login if ($LASTEXITCODE -ne 0) { throw 'az login failed.' } $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-Az rest --method GET --url 'https://graph.microsoft.com/v1.0/organization?$select=displayName').value) | Select-Object -First 1).displayNameWrite-Note "tenant: $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"if (-not $Force -and -not $WhatIfPreference) { $answer = Read-Host " Create '$AppName' in '$tenantName'? (y/n)" if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# -- 2. app registration and service principal ----------------------------------------Write-Step "2/2 App registration '$AppName'"$apps = @(Invoke-Az ad app list --display-name $AppName | Where-Object { $_.displayName -eq $AppName })if ($apps.Count -gt 1) { throw "There are $($apps.Count) app registrations named '$AppName'. Remove the extra ones, or use -AppName." }$reg = $apps | Select-Object -First 1if ($reg) { Write-Skip "app registration exists (appId $($reg.appId))" }elseif ($PSCmdlet.ShouldProcess($AppName, 'Create the app registration')) { $reg = Invoke-Az ad app create --display-name $AppName --sign-in-audience AzureADMyOrg Write-Ok "created the app registration (appId $($reg.appId))"}if (-not $reg) { Write-Note 'Dry run ends here: the app does not exist yet.'; return }$appId = $reg.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if ($sp) { Write-Skip "service principal exists ($($sp.id))" }elseif ($PSCmdlet.ShouldProcess($appId, 'Create the service principal')) { for ($attempt = 1; -not $sp; $attempt++) { # a new app needs a few seconds to replicate try { $sp = Invoke-Az ad sp create --id $appId } catch { if ($attempt -ge 4) { throw }; Start-Sleep -Seconds 10 } } Write-Ok "created the service principal ($($sp.id))"}# -- next -----------------------------------------------------------------------------$grant = "./Grant-HiveBDCMailAccess.ps1 -AppId $appId -SenderMailbox <mailbox@domain>"Write-Host "`nDONE, the app has no permissions yet" -ForegroundColor YellowWrite-Host " Tenant ID $tenantId"Write-Host " Client ID $appId"Write-Note ''Write-Note 'Step 2, assign the permissions:'Write-Note " $grant"Write-Note 'Client secret (shown once, enter it straight into the Hive BDC dashboard):'Write-Note " az ad app credential reset --id $appId --append --display-name HiveBDC --years 2 --query password -o tsv"2Assign the permissions
Allows the app in Exchange Online to send as the one mailbox you name, with no tenant-wide Mail.Send consent in Entra ID. Use the client ID from step 1. Needs Exchange Administrator.
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/Grant-HiveBDCMailAccess.ps1 -OutFile Grant-HiveBDCMailAccess.ps1./Grant-HiveBDCMailAccess.ps1 -AppId <client-id> -SenderMailbox invoices@contoso.com<#.SYNOPSIS Step 2 of 2 for mail: allows the Hive BDC Mail app to send as ONE mailbox, and as no other..DESCRIPTION Run in Azure Cloud Shell (PowerShell) after New-HiveBDCMailApp.ps1. Steps, each skipped when already in place: 1. Azure CLI: show the tenant, the app and the mailbox, and ask before changing anything. 2. Exchange Online: RBAC for Applications, the role "Application Mail.Send" limited to a management scope that contains only -SenderMailbox. The app gets NO Mail.Send consent in Entra ID, because an Entra consent is tenant-wide and RBAC grants add to it instead of narrowing it; an existing Entra consent is removed. Tenants without RBAC for Applications get the older application access policy, which does restrict an Entra consent. Role: Exchange Administrator (plus Privileged Role Administrator only to remove an old Entra consent, or for the access policy fallback). -WhatIf shows the plan only..EXAMPLE ./Grant-HiveBDCMailAccess.ps1 -AppId 11111111-2222-3333-4444-555555555555 -SenderMailbox invoices@contoso.com#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param( # Application (client) ID printed by New-HiveBDCMailApp.ps1. [Parameter(Mandatory = $true)] [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')] [string] $AppId, [Parameter(Mandatory = $true)] [ValidatePattern('^[^@\s]+@[^@\s]+\.[^@\s]+$')] [string] $SenderMailbox, # Prefix of the Exchange objects (scope, role assignment, security group). [ValidatePattern('^[A-Za-z0-9-]{3,40}$')] [string] $Name = 'HiveBDCMail', [switch] $UseApplicationAccessPolicy, [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')] [string] $TenantId, # Do not ask before changing the tenant. [switch] $Force)$ErrorActionPreference = 'Stop'$GraphAppId = '00000003-0000-0000-c000-000000000000' # Microsoft Graph, same in every tenant$GraphV1 = 'https://graph.microsoft.com/v1.0'function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host " [ok] $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host " [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host " $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az { $output = & az @args --only-show-errors --output json if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." } $text = ($output | Out-String).Trim() if (-not $text) { return } $parsed = $text | ConvertFrom-Json return $parsed # return, not the pipeline, so a JSON array arrives as its items}# One Microsoft Graph call through 'az rest'. The body goes through a file because# Windows PowerShell 5.1 and az.cmd both mangle quotes in JSON arguments.function Invoke-GraphAz { param([string] $Method, [string] $Path, $Body) $azArgs = @('rest', '--method', $Method, '--url', "$GraphV1/$Path") $bodyFile = $null if ($null -ne $Body) { $bodyFile = [IO.Path]::GetTempFileName() [IO.File]::WriteAllText($bodyFile, ($Body | ConvertTo-Json -Depth 8)) $azArgs += @('--body', "@$bodyFile", '--headers', 'Content-Type=application/json') } try { return Invoke-Az @azArgs } finally { if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -ErrorAction SilentlyContinue } }}function Get-AzCliAccount { $ErrorActionPreference = 'Continue' # 'not signed in' arrives on stderr $text = (& az account show --output json 2>$null | Out-String).Trim() if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}function Test-Cmdlet { param([string] $CmdletName) [bool](Get-Command $CmdletName -ErrorAction SilentlyContinue) }if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/2 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) { throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) { $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none') if ($TenantId) { $login += @('--tenant', $TenantId) } if ($useDeviceCode) { $login += '--use-device-code' } & az @login if ($LASTEXITCODE -ne 0) { throw 'az login failed.' } $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-GraphAz GET 'organization?$select=displayName').value) | Select-Object -First 1).displayNameWrite-Note "tenant: $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"$app = Invoke-Az ad app show --id $AppId$AppName = $app.displayName$appId = $app.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if (-not $sp) { throw "The app $appId has no service principal. Run New-HiveBDCMailApp.ps1 first." }Write-Note "app: $AppName ($appId)"Write-Note "mailbox: $SenderMailbox"if (-not $Force -and -not $WhatIfPreference) { $answer = Read-Host " Allow it to send as $SenderMailbox only? (y/n)" if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# The tenant-wide Entra consent, if someone granted one; step 2 decides what happens to it.$graphSp = Invoke-Az ad sp show --id $GraphAppId$mailSend = @($graphSp.appRoles | Where-Object { $_.value -eq 'Mail.Send' -and $_.allowedMemberTypes -contains 'Application' }) | Select-Object -First 1$entraGrant = @((Invoke-GraphAz GET "servicePrincipals/$($sp.id)/appRoleAssignments").value | Where-Object { $_.appRoleId -eq $mailSend.id -and $_.resourceId -eq $graphSp.id }) | Select-Object -First 1# -- 3. Exchange Online ---------------------------------------------------------------Write-Step '2/2 Exchange Online: send as one mailbox only'if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) { Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser -Force -AllowClobber}Import-Module ExchangeOnlineManagementif ($useDeviceCode) { Connect-ExchangeOnline -Device -ShowBanner:$false } else { Connect-ExchangeOnline -ShowBanner:$false }if (Test-Cmdlet 'Get-ConnectionInformation') { $exoTenant = @(Get-ConnectionInformation)[0].TenantID if ($exoTenant -and "$exoTenant" -ne $tenantId) { Disconnect-ExchangeOnline -Confirm:$false | Out-Null throw "Exchange Online signed in to tenant $exoTenant, but the app is in $tenantId." }}$mailbox = Get-Mailbox -Identity $SenderMailbox -ErrorAction SilentlyContinueif (-not $mailbox) { throw "The mailbox '$SenderMailbox' was not found in Exchange Online." }$useRbac = (Test-Cmdlet 'New-ServicePrincipal') -and (Test-Cmdlet 'New-ManagementRoleAssignment') -and -not $UseApplicationAccessPolicyif ($useRbac) { $scopeName = "$Name-Scope" $assignmentName = "$Name-MailSend" if (Get-ServicePrincipal -Identity $appId -ErrorAction SilentlyContinue) { Write-Skip 'registered in Exchange Online' } elseif ($PSCmdlet.ShouldProcess($appId, 'Register the service principal in Exchange Online')) { # Exchange needs the service principal's OBJECT id, not the application id. New-ServicePrincipal -AppId $appId -ObjectId $sp.id -DisplayName $AppName | Out-Null Write-Ok 'registered in Exchange Online' } # Custom scopes need the one-time switch Enable-OrganizationCustomization, which tenants # that never customised Exchange have off ("isn't currently allowed in your organization"). if (-not (Get-OrganizationConfig).IsDehydrated) { Write-Skip 'organisation customization is enabled' } elseif ($PSCmdlet.ShouldProcess('Exchange Online organisation', 'Enable-OrganizationCustomization (one-time, permanent)')) { Enable-OrganizationCustomization Write-Ok 'enabled organisation customization (needed once for custom scopes)' } $scope = Get-ManagementScope -Identity $scopeName -ErrorAction SilentlyContinue if ($scope) { Write-Skip "scope '$scopeName': $($scope.RecipientFilter)" if ($scope.RecipientFilter -notmatch [regex]::Escape($SenderMailbox)) { Write-Warning "The scope '$scopeName' does NOT match $SenderMailbox. Review it, or use another -Name." } } elseif ($PSCmdlet.ShouldProcess($scopeName, "Create a management scope with only $SenderMailbox")) { # Doubled apostrophes keep an address with ' from breaking the filter. $filter = "PrimarySmtpAddress -eq '{0}'" -f $SenderMailbox.Replace("'", "''") try { New-ManagementScope -Name $scopeName -RecipientRestrictionFilter $filter -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Message -notmatch 'OrganizationCustomization') { throw } # Exchange applies the switch with a delay of up to about an hour. Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue | Out-Null Write-Host '' Write-Host ' Exchange Online has not applied the customization switch yet; that takes up to an hour.' -ForegroundColor Yellow Write-Host ' Run this script again later with the same parameters. Everything done so far is skipped,' -ForegroundColor Yellow Write-Host ' and the app cannot send mail until it has finished.' -ForegroundColor Yellow return } Write-Ok "created the scope '$scopeName'" } if (Get-ManagementRoleAssignment -Identity $assignmentName -ErrorAction SilentlyContinue) { Write-Skip "role assignment '$assignmentName'" } elseif ($PSCmdlet.ShouldProcess($assignmentName, "Assign 'Application Mail.Send' limited to $scopeName")) { New-ManagementRoleAssignment -Name $assignmentName -App $appId -Role 'Application Mail.Send' ` -CustomResourceScope $scopeName | Out-Null Write-Ok "assigned 'Application Mail.Send' for $SenderMailbox" } # An Entra consent would add tenant-wide send-as on top of the scoped role. if (-not $entraGrant) { Write-Skip 'no tenant-wide Mail.Send consent in Entra ID (correct)' } elseif ($PSCmdlet.ShouldProcess($AppName, 'Remove the tenant-wide Mail.Send consent from Entra ID')) { Invoke-GraphAz DELETE "servicePrincipals/$($sp.id)/appRoleAssignments/$($entraGrant.id)" | Out-Null Write-Ok 'removed the tenant-wide Mail.Send consent from Entra ID' } $verify = "Test-ServicePrincipalAuthorization -Identity $appId -Resource $SenderMailbox"}else { # Older tenants: Entra consent for Mail.Send, restricted by an application access # policy to a mail-enabled SECURITY group (a Microsoft 365 group does not work). if (-not (Test-Cmdlet 'New-ApplicationAccessPolicy')) { throw 'Neither RBAC for Applications nor application access policies are available. Update ExchangeOnlineManagement and retry.' } $groupAlias = $Name.ToLowerInvariant() $groupAddress = "$groupAlias@$($SenderMailbox.Split('@')[1])" if (Get-DistributionGroup -Identity $groupAddress -ErrorAction SilentlyContinue) { Write-Skip "group $groupAddress" } elseif ($PSCmdlet.ShouldProcess($groupAddress, 'Create the mail-enabled security group')) { New-DistributionGroup -Name $Name -Alias $groupAlias -PrimarySmtpAddress $groupAddress -Type Security | Out-Null Write-Ok "created the group $groupAddress" } $members = @(Get-DistributionGroupMember -Identity $groupAddress -ErrorAction SilentlyContinue | ForEach-Object { $_.PrimarySmtpAddress }) if ($members -contains $mailbox.PrimarySmtpAddress) { Write-Skip "$SenderMailbox is a member" } elseif ($PSCmdlet.ShouldProcess($groupAddress, "Add $SenderMailbox")) { Add-DistributionGroupMember -Identity $groupAddress -Member $SenderMailbox Write-Ok "added $SenderMailbox to the group" } if (@(Get-ApplicationAccessPolicy -ErrorAction SilentlyContinue | Where-Object { $_.AppId -eq $appId })) { Write-Skip 'application access policy' } elseif ($PSCmdlet.ShouldProcess($appId, "Restrict the app to $groupAddress")) { New-ApplicationAccessPolicy -AppId $appId -PolicyScopeGroupId $groupAddress -AccessRight RestrictAccess ` -Description "Hive BDC may send only as members of $groupAddress" | Out-Null Write-Ok 'created the application access policy' } # The consent comes last, so it is never in place without the policy that limits it. if ($entraGrant) { Write-Skip 'Mail.Send consented in Entra ID' } elseif ($PSCmdlet.ShouldProcess($AppName, 'Grant admin consent for Mail.Send')) { Invoke-GraphAz POST "servicePrincipals/$($sp.id)/appRoleAssignments" @{ principalId = $sp.id; resourceId = $graphSp.id; appRoleId = $mailSend.id } | Out-Null Write-Ok 'Mail.Send consented, limited by the policy above' } $verify = "Test-ApplicationAccessPolicy -Identity $SenderMailbox -AppId $appId"}Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue | Out-Null# -- next -----------------------------------------------------------------------------Write-Host "`nDONE" -ForegroundColor YellowWrite-Host " Tenant ID $tenantId"Write-Host " Client ID $appId"Write-Host " Send from $SenderMailbox"Write-Note 'Hive BDC dashboard: Settings > Connections > Document mail, then Test mail.'Write-Note 'Exchange needs up to 30 minutes to apply this; until then sending can fail with ErrorAccessDenied.'Write-Note "Check later: $verify"Hive BDC runs with a licence from Balsoft. Without one, the dashboard opens but no documents are processed. Get in touch for a licence or a test installation.
Contact us