Friday, September 23, 2016

Add Office 365: Exchange Online e-mail address @contoso.mail.onmicrosoft.com on every mailbox with PowerShell

Scenario

To handle mailflow in a Exchange Hybrid scenario every mailbox needs an e-mail routing address matching the tenant e-mail domain name (contosotenant.mail.onmicrosoft.com).

Hybrid Configuration Wizard (HCW) adds this new configuration automatically and the new e-mail address on every mailbox which has the e-mail address policy enabled on it ("Automatically update email addresses based on the email address policy applied to this recipient" checkbox). Challenge appears when a lot of mailboxes within Exchange organization do not have the e-mail address policy enabled. I hope Exchange HCW development team will fix this behavior soon.

When you try to move mailboxes from your on-premises environment to Exchange Online, you receive the following error message without @contosotenant.mail.onmicrosoft.com-like smtp alias:
The target mailbox doesn't have an SMTP proxy matching '<domain>.mail.onmicrosoft.com'
Solution

Following simple PowerShell script will automatically add the new e-mail address in format  of "alias@contosotenant.mail.onmicrosoft.com" on every mailbox within your Exchange Organization without enabling the e-mail address policy.

$mailboxes=Get-Mailbox -ResultSize Unlimited | where {!$_.EmailAddressPolicyEnabled} | select DisplayName, Alias, PrimarySmtpAddress, Identity

foreach ($mailbox in $mailboxes) {

$alias=$mailbox.alias
$email=$alias + “@contosotenant.mail.onmicrosoft.com”
Set-mailbox $mailbox.Identity -EmailAddresses @{add=$email}
}

$mailboxes | Export-Csv -Path "$env:USERPROFILE\Desktop\mailboxes_changed.csv"