Replacing a Mimecast, Proofpoint, Barracuda, Cisco Secure Email or FortiMail-style gateway with Exchange Online Protection (EOP) is a routing project with a security tuning project inside it. Get the order wrong and inbound mail starts bouncing the moment the MX record changes. In this post I'll walk through the cutover phase by phase, with a message trace or header check for every step and a rollback plan you can actually run.
Errors this guide fixes
550 5.7.51 TenantInboundAttribution; There is a partner connector configured that matched the message's recipient domainNDR550 5.4.1 Recipient address rejected: Access denied. AS(201806281)NDR+1 more guide550 5.7.64 TenantAttribution; Relay Access DeniedNDR / SMTP log550 5.7.68 TenantInboundAttribution; Direct Send not allowed for this organization from unauthorized sourcesNDR
Status (October 2026): Microsoft's three-phase guide for moving from a third-party protection service to Defender for Office 365 (Prepare, Set up, Onboard) is still the reference. Two newer changes matter on cutover day: domains added to Microsoft 365 since July 2026 get MX host names under mx.microsoft instead of mail.protection.outlook.com (Message center MC1048624), and Exchange Online can now reject Direct Send traffic for the whole tenant. Re-check Microsoft's pages before you start.
How the migration works#
Today the gateway owns your MX record, filters inbound mail and hands the rest to Exchange Online through an inbound connector that's usually locked to the gateway's IP addresses or certificate. Most setups also have a mail flow rule that sets the spam confidence level (SCL) to -1, so Microsoft 365 doesn't filter the same message twice. The migration unwinds this in a safe order: test Microsoft's protection on live traffic while the gateway still delivers, move the MX record, then clean up.
Microsoft's guide is written for Defender for Office 365 Plan 2, but the routing steps are identical with EOP alone; you skip Safe Links, Safe Attachments, impersonation protection and Threat Explorer. It leaves outbound and relay mail out of scope, so I've added those, plus hybrid and decommissioning. Newer Microsoft Learn pages call EOP's protections the built-in security features for all cloud mailboxes; it's the same service.
| Phase | MX points to | What you change | You're done when |
|---|---|---|---|
| 1. Inventory and mapping | Gateway | Nothing in production; export the gateway's settings, document Microsoft 365's | Every gateway rule has a decision: recreate, replace or drop |
| 2. Set up | Gateway | Enhanced Filtering, a scoped SCL -1 rule with pilot exceptions, user reporting, pilot policies | Pilot users get Microsoft verdicts; everyone else shows SFV:SKN |
| 3. Pilot and extend | Gateway | Tuning, larger pilot waves, policies for everyone, SCL -1 rule off | All mail is filtered by Microsoft 365 at an acceptable false-positive rate |
| 4. Cutover | Microsoft 365 | Connector restrictions off, MX record switched | Message trace shows senders' own IP addresses, not the gateway's |
| 5. Outbound and authentication | Microsoft 365 | DKIM on, SPF updated, outbound connector off | External recipients see dkim=pass for your domain |
| 6. Decommission | Microsoft 365 | Connectors, rules, DNS, firewall and contract cleaned up | Nothing references the gateway any more |
Prerequisites#
- Exchange Administrator and Security Administrator in Microsoft Entra ID, or the matching Exchange Online role groups and Email & collaboration roles.
- Exchange Online PowerShell with the ExchangeOnlineManagement module; see my Exchange Online PowerShell V3 guide.
- Access to every DNS zone you'll change, and time to lower TTLs a few days early.
- Gateway admin access, the full list of its public sending IP addresses (or its TLS certificate name) from the vendor's documentation, and a contract that outlasts your rollback window.
- A clear license picture. EOP comes with Exchange Online; Safe Links, Safe Attachments, impersonation protection and the investigation tools need Defender for Office 365.
- Dates and owners for the pilot, the cutover window and the rollback window.
Phase 1: Inventory the gateway and map its features#
1. Export the gateway's configuration first#
Microsoft's advice is to inventory the old service before you change anything, because you probably won't be able to read its settings once the subscription ends. Capture policies and exceptions, allow and block lists, partner TLS rules, relay rules, outbound routing, DKIM selectors, archive or journal feeds, link rewriting, banners, digests and API integrations. Don't recreate it all, though. Microsoft suggests two buckets: connection and content filtering, which you'll mostly no longer need, and business routing, which you'll rebuild as mail flow rules, connectors or spoof intelligence exceptions. Let the pilot decide which overrides survive.
2. Record what Microsoft 365 already does#
Connect-ExchangeOnline
# Which inbound connector carries gateway mail, and is it locked to the gateway?
Get-InboundConnector | Format-List Name, Enabled, ConnectorType, SenderDomains, SenderIPAddresses,
TlsSenderCertificateName, RequireTls, RestrictDomainsToIPAddresses, RestrictDomainsToCertificate,
EFSkipLastIP, EFSkipIPs, EFUsers
# Does outbound mail leave through the gateway?
Get-OutboundConnector | Format-List Name, Enabled, ConnectorType, RecipientDomains, SmartHosts,
UseMXRecord, IsTransportRuleScoped, TlsSettings, RouteAllMessagesViaOnPremises
# Rules that bypass filtering or route through a connector
Get-TransportRule | Where-Object { $_.SetSCL -eq -1 -or $_.RouteMessageOutboundConnector } |
Format-List Name, State, Priority, SetSCL, SenderIpRanges, ExceptIfSentToMemberOf, RouteMessageOutboundConnector
# Domains, IP allow list, ARC, DKIM, journaling and Direct Send
Get-AcceptedDomain | Format-Table DomainName, DomainType, Default
Get-HostedConnectionFilterPolicy | Format-List Name, IPAllowList
Get-ArcConfig | Format-List ArcTrustedSealers
Get-DkimSigningConfig | Format-Table Name, Enabled, Status
Get-JournalRule | Format-Table Name, Enabled, JournalEmailAddress
Get-OrganizationConfig | Format-List RejectDirectSendLook hard at old allow lists, IP allow entries and bypass rules. Microsoft warns that settings the gateway made irrelevant start to matter again once you rely on Microsoft 365 filtering, so remove or simplify them now.
3. Map each feature to its replacement#
| Typical gateway feature | Replacement in Microsoft 365 | Note |
|---|---|---|
| Connection filtering, IP reputation | Built-in connection filtering and the connection filter policy | Don't copy the gateway's IP allow lists |
| Spam and bulk scoring | Anti-spam policies (spam actions, bulk threshold) | Decide Junk Email folder or quarantine |
| Antivirus, attachment type blocking | Anti-malware policy with the common attachments filter | Always on; not affected by the SCL -1 rule |
| Attachment sandboxing | Safe Attachments | Defender for Office 365 |
| Link rewriting, time-of-click checks | Safe Links | Defender for Office 365; never wrap links twice |
| Impersonation and BEC protection | Anti-phishing policies: spoof intelligence, impersonation, mailbox intelligence | Spoof protection is in EOP; impersonation needs Defender for Office 365 |
| Sender, domain, URL and file lists | Tenant Allow/Block List | Recreate only what the pilot proves you need |
| Quarantine digest | Quarantine policies with quarantine notifications | Match the experience users know |
| Personal allow and block lists | Outlook Safe Senders and Blocked Senders | They don't migrate; tell users |
| External banner or subject tag | Outlook external sender callout, first contact safety tip, or a mail flow rule | Move it before the pilot |
| Disclaimers | Mail flow rules, or a signature product | Test with the outbound switch |
| Enforced TLS with partners | Partner connectors (inbound TLS requirement, outbound TLS settings) | One connector pair per partner |
| Recipient validation | Directory-Based Edge Blocking on Authoritative domains | Every recipient must exist in the directory |
| Outbound DLP, encryption portal | Microsoft Purview DLP and Message Encryption | Depends on your licenses |
| Outbound DKIM signing | DKIM signing in Microsoft 365 | Enable before you move outbound mail |
| Archiving, continuity, large-file sending | No EOP equivalent | Decide separately and export before the contract ends |
| Phishing simulations | Attack simulation training (Plan 2), or the advanced delivery policy for third-party simulations | Never use allow lists for simulations |
4. Decide the user experience before the pilot#
- Junk Email folder or quarantine. Microsoft's Standard settings generally send spam and bulk mail to the Junk Email folder, while gateway users often expect an empty Junk folder and a digest. Pick one, configure quarantine policies and notifications to match, and tell users. See handling false-positive quarantined email.
- Bulk mail for VIPs. Personal bulk preferences don't carry over; Microsoft suggests mail flow rules that filter bulk email for people who won't unsubscribe themselves.
- Third-party phishing simulations and SecOps mailboxes belong in Email & collaboration › Policies & rules › Threat policies › Advanced delivery, not in allow lists.
Phase 2: Configure EOP and Defender while the gateway still owns MX#
1. Keep the connector locked and turn on Enhanced Filtering#
Leave the restriction on the gateway's inbound connector in place for now; it stops attackers from bypassing the gateway. Then turn on Enhanced Filtering for Connectors on that connector so Microsoft 365 sees each message's real source. Microsoft calls it required for Defender for Office 365 and asks for the public IP addresses of all third-party services and on-premises hosts that route inbound mail to Microsoft 365; the Inbound messages report helps you find the connector. My Enhanced Filtering for Connectors guide has the full procedure.
2. Scope the SCL -1 rule and add pilot exceptions#
Keep the bypass rule during the migration. With it in place, Threat Explorer shows what Microsoft 365 would have done without changing what users receive, and exceptions to the rule move people onto Microsoft filtering one group at a time. If you bypass filtering another way, such as an IP Allow List entry, Microsoft recommends switching to a bypass rule while all internet mail comes through the gateway.
The rule must match only mail that passed through the gateway: a header and value unique to your organization for a cloud service, or source IP addresses for an on-premises appliance. Never rely on the MX record alone, because senders can deliver directly to Microsoft 365.
# Pilot groups (names from Microsoft's guide; your own convention works too)
$pilot = "MDOPilot_SafeAttachments","MDOPilot_SafeLinks","MDOPilot_SpamPhish_Standard","MDOPilot_SpamPhish_Strict"
$pilot | ForEach-Object { New-DistributionGroup -Name $_ }
Add-DistributionGroupMember -Identity "MDOPilot_SpamPhish_Standard" -Member "pilot.user@contoso.com"
# Cloud gateway: match a header and value that only your gateway adds (example names)
New-TransportRule -Name "Bypass spam filtering - mail from gateway" `
-HeaderContainsMessageHeader "X-Contoso-Gateway" -HeaderContainsWords "a-long-random-value" `
-SetSCL -1 -ExceptIfSentToMemberOf $pilot
# On-premises appliance: use its public IP addresses as the condition instead
# New-TransportRule -Name "..." -SenderIpRanges 203.0.113.10,203.0.113.11 -SetSCL -1 -ExceptIfSentToMemberOf $pilot
# Already have a rule? Add the pilot exceptions to it
Set-TransportRule -Identity "Bypass spam filtering - mail from gateway" -ExceptIfSentToMemberOf $pilotAnti-malware protection isn't affected by this rule, so malware scanning stays on for everyone.
3. Set up user reporting and the pilot policies#
- User reporting. In Settings › Email & collaboration › User reported settings, choose a reporting mailbox, and make sure pilot users have the built-in Report button in Outlook or a supported third-party tool. Reports are your feedback loop; see user-reported messages.
- Custom pilot policies, not presets. Create anti-spam, anti-phishing, Safe Attachments and Safe Links policies close to Microsoft's Standard and Strict recommendations, scoped to the pilot groups, with Strict at a higher priority. You can't customize the actions in preset security policies, and the pilot is exactly where you'll want to. Compare your settings in Email & collaboration › Policies & rules › Threat policies › Configuration analyzer.
- Start with Safe Attachments (minimal configuration, extremely low chance of false positives), then Safe Links with a smaller group.
- Anti-phishing actions. Spoof detections go to the Junk Email folder (Standard) or quarantine (Strict). Set user impersonation, domain impersonation and mailbox intelligence to Don't apply any action for now and watch the impersonation insight instead.
- No double wrapping. Rewriting links that are already rewritten isn't supported. Turn off the gateway's link wrapping for Safe Links pilot users, or exclude its rewrite domain in the Safe Links policy. Check a non-pilot mailbox too, because the Built-in protection preset gives Safe Links protection to recipients who aren't in any other Safe Links policy.
- Optionally, exempt pilot users from gateway filtering, so Microsoft 365 isn't just filtering what the gateway missed.
4. Move message-modifying features into Microsoft 365#
Subject tags, banners and wrapped links break DKIM for senders that sign, confuse spoof intelligence and cause false positives. Move them into Microsoft 365 before you judge the pilot: the Outlook external sender callout with first contact safety tips or a mail flow rule (see mail flow rules that don't backfire), and Safe Links instead of the gateway's link wrapping. If a modification must stay until cutover and the gateway supports ARC, add the gateway as a trusted ARC sealer.
Verify phase 2#
Send a message from an external mailbox to one pilot user and one non-pilot user, then compare the headers (the Message Header Analyzer makes this easier):
- Non-pilot user:
SFV:SKNinX-Forefront-Antispam-Report, meaning spam filtering was bypassed by a mail flow rule. - Pilot user:
SFV:NSPMorSFV:SPM, meaning Microsoft 365 made its own decision. - Both:
X-MS-Exchange-ExternalOriginalInternetSenderis present (X-MS-Exchange-SkipListedInternetSenderalone means the recipient is outside the Enhanced Filtering scope), andAuthentication-Resultsevaluates the original sender, withcompauth=passand a 1xx reason for well-configured domains.
A compauth=none reason=905 result means DMARC wasn't enforced because of complex routing, so Microsoft 365 isn't seeing past the gateway; recheck the Enhanced Filtering IP list. In message trace, internet mail to the pilot user should still show a gateway address in FromIP:
Get-MessageTraceV2 -RecipientAddress pilot.user@contoso.com -StartDate (Get-Date).AddHours(-2) -EndDate (Get-Date) |
Format-Table Received, SenderAddress, FromIP, StatusPhase 3: Run the pilot, then extend protection to everyone#
- Bring the security team in early. Quarantine, message trace and, with Plan 2, Threat Explorer, Advanced Hunting and Incidents become their daily tools.
- Tune spoof intelligence. Gateway overrides often hide partners with broken SPF, DKIM or DMARC. Start with sources outside your Enhanced Filtering ranges and the highest-volume, highest-impact senders, and allow genuine ones in the Tenant Allow/Block List.
- Turn on impersonation actions one at a time: mailbox intelligence (Junk Email folder for Standard, quarantine for Strict), then user impersonation, then domain impersonation (quarantine for both), observing the results between each.
- Measure with user reports in Actions & submissions › Submissions › User reported. Submit misclassified messages to Microsoft, fix the specific detection instead of adding broad allows, and review overrides in the Threat protection status report.
- Grow the pilot in waves.
- Extend the policies to everyone. Split all users between the Standard and Strict preset security policies, making sure nobody falls outside both, or widen your custom policies, ideally by domain. Only a user's primary SMTP domain decides which policy applies, so cover every primary domain. See Standard vs Strict presets for precedence.
- Disable the SCL -1 rule, but don't delete it; it's part of your rollback.
Disable-TransportRule -Identity "Bypass spam filtering - mail from gateway" -Confirm:$false
Get-TransportRule -Identity "Bypass spam filtering - mail from gateway" | Format-List Name, StateEvery message is now filtered twice; Microsoft suggests pausing here to collect data and tune. Good looks like: the rule is Disabled and test messages to non-pilot users show a real SFV verdict instead of SFV:SKN.
Phase 4: Cutover day, the MX switch#
Two days before, or earlier#
- Lower the TTL on the MX record, for example to 300 seconds, and wait for the old TTL to expire. Microsoft recommends this for a faster switch and a possible rollback, and warns that propagation can take up to 48 hours.
- Copy the exact MX value from the Microsoft 365 admin center under Settings › Domains, then the domain and its DNS records. Don't type
contoso-com.mail.protection.outlook.comfrom memory: domains added since July 2026 get a host name ending inmx.microsoft, and automation should read themailExchangevalue from the Microsoft Graph serviceConfigurationRecords API. - Update MTA-STS if you publish a policy, because senders that enforce it won't deliver to an MX host it doesn't list. Add the Microsoft host as an
mxline, set the mode to testing, change theidin the_mta-stsTXT record and wait formax_ageto pass. - Check recipient validation. If the gateway validated recipients, make sure each domain is Authoritative in Microsoft 365 and every valid address exists in the directory; Directory-Based Edge Blocking rejects the rest (see my 5.4.1 guide).
- Start with less frequently used domains, as Microsoft suggests, and pause to monitor before the large ones.
- Brief the help desk and users on quarantine, notifications and the Report button.
- Confirm with the vendor that the gateway will keep accepting and relaying mail to Microsoft 365 while DNS caches still point to it.
Tip: Keep DNSSEC and inbound SMTP DANE out of cutover day. If your zone is DNSSEC-signed and the Microsoft MX value already ends in mx.microsoft, DNSSEC extends to it automatically. For an older domain that still uses a mail.protection.outlook.com value, enable DNSSEC and DANE later with Enable-DnssecForVerifiedDomain and Enable-SmtpDaneInbound; Microsoft's procedure assumes a single MX record with no fallback.
Cutover steps#
- Confirm phase 3 is complete: the SCL -1 rule is disabled and policies cover every user.
- Turn off the connector restrictions. Microsoft is explicit: if the inbound connector from the protection service is a Partner connector with
RestrictDomainsToIPAddressesorRestrictDomainsToCertificateturned on, all mail delivery to your domains fails after you switch the MX record. Keep the connector itself enabled, so mail the gateway still relays keeps its Enhanced Filtering treatment.Left on, the restriction rejects every sender whose DNS cache has already moved to Microsoft 365, with this NDR:PowerShellSet-InboundConnector -Identity "From mail gateway" -RestrictDomainsToIPAddresses $false -RestrictDomainsToCertificate $false # Good: the Partner connector is Enabled with both restrictions False Get-InboundConnector | Format-Table Name, ConnectorType, Enabled, RequireTls, RestrictDomainsToIPAddresses, RestrictDomainsToCertificateText550 5.7.51 TenantInboundAttribution; There is a partner connector configured that matched the message's recipient domain. The connector had either the RestrictDomainsToIPAddresses or RestrictDomainsToCertificate set - Decide about TLS.
RequireTlsrejects messages that aren't sent over TLS on a Partner connector, and sender domain*covers every sender. Keep it only if you want to require TLS from the whole internet. - Leave hybrid connectors alone. Microsoft notes that an OnPremises connector used for hybrid doesn't need changes; just make sure no Partner connector is left behind.
- Switch the MX record to the single Microsoft value and the priority the admin center shows. Don't keep the gateway as a backup MX: Microsoft says split routing technically works but makes troubleshooting much harder, and doesn't recommend it.
Verify the cutover#
Resolve-DnsName -Name contoso.com -Type MX
Resolve-DnsName -Name contoso.com -Type MX -Server 8.8.8.8
# Who delivered mail in the last hour? Gateway IPs should sink down this list
Get-MessageTraceV2 -StartDate (Get-Date).AddHours(-1) -EndDate (Get-Date) -ResultSize 5000 |
Group-Object FromIP | Sort-Object Count -Descending | Select-Object -First 15 Count, Name- DNS: both resolvers return only the Microsoft host.
- Connectivity: the Inbound SMTP Email test in the Microsoft Remote Connectivity Analyzer passes, and its test steps show the Microsoft host.
- Message trace: for inbound mail,
FromIPis the public IP address of the server that sent it, so senders' own servers appear while the gateway's share shrinks over the next 48 hours. - Headers on a new external test message: no
X-MS-Exchange-SkipListedInternetSender, because the message didn't come through the gateway connector;CIPinX-Forefront-Antispam-Reportis the sender's own server;SFVis a real verdict; andcompauth=passcarries a 1xx reason rather than 905. - NDRs: ask a few partners to confirm delivery, and treat any report of 5.7.51 or 5.4.1 as urgent.
- TTL: once everything is stable, restore a normal MX TTL; Microsoft's DANE procedure uses 3,600 seconds.
Phase 5: Outbound routing, SPF, DKIM and DMARC#
If outbound mail goes through the gateway, usually through a Partner outbound connector with recipient domain * and the gateway as smart host, Microsoft says to remove or change that connector. Make it a separate change once inbound has settled:
- Replace outbound features first: disclaimers, DLP, encryption and large-file sending. Microsoft Purview DLP and Message Encryption are the native options, license permitting.
- Turn on DKIM for each custom domain before the switch, on the DKIM tab of Email & collaboration › Policies & rules › Threat policies › Email authentication settings. Copy both CNAME targets exactly (domains added since May 2025 use a newer format), and make sure the gateway's selectors aren't also named
selector1orselector2. See my SPF, DKIM and DMARC guide. - Add Microsoft to SPF alongside the gateway, within the limit of ten DNS lookups.
- Switch: change any mail flow rule that routes through the gateway connector, then disable the connector.
- Keep DMARC as it is and watch the aggregate reports. Defender for Office 365 doesn't aggregate them, so use a reporting service.
- After the rollback window, remove the gateway's SPF include and its DKIM selector records.
# DKIM: good is Enabled True and Status Valid
Get-DkimSigningConfig -Identity contoso.com | Format-List Name, Enabled, Status, Selector1CNAME, Selector2CNAME
Set-DkimSigningConfig -Identity contoso.com -Enabled $true # once both CNAMEs resolve
# Rules that still route through the gateway connector
Get-TransportRule | Where-Object { $_.RouteMessageOutboundConnector } | Format-Table Name, State, RouteMessageOutboundConnector
Set-OutboundConnector -Identity "To mail gateway" -Enabled $false
# Outbound check: ToIP should belong to the recipient's mail servers, not the gateway
Get-MessageTraceV2 -SenderAddress user@contoso.com -StartDate (Get-Date).AddHours(-1) -EndDate (Get-Date) |
Format-Table Received, RecipientAddress, ToIP, StatusDuring the transition: v=spf1 include:spf.protection.outlook.com include:<gateway SPF include> -all
After the rollback window: v=spf1 include:spf.protection.outlook.com -allGood looks like this in an external recipient's headers: spf=pass from a Microsoft IP address, dkim=pass with header.d=contoso.com, and dmarc=pass.
Hybrid and on-premises routing#
With Exchange Server in the picture, the cutover changes more than the entry point. Find your current path:
| Current path | What changes at cutover | What to check |
|---|---|---|
| MX › gateway › Exchange Online; on-premises mailboxes reached through the hybrid connectors | Only where internet mail enters; Exchange Online already delivers to on-premises through the hybrid outbound connector | A test message to an on-premises mailbox arrives without deferrals |
| MX › gateway › Exchange Server › Exchange Online | Internet mail for on-premises mailboxes now arrives from Exchange Online instead of the gateway | Firewall and receive connectors accept Exchange Online on port 25 with TLS; on-premises rules that trusted the gateway's IPs; Enhanced Filtering IPs on the hybrid inbound connector |
Centralized mail transport (RouteAllMessagesViaOnPremises is True) | Inbound internet mail goes on-premises first and comes back; outbound cloud mail leaves through on-premises | Whether you still need it. Enhanced Filtering doesn't support the out-and-back path; change it by running the Hybrid Configuration Wizard again |
- On-premises outbound mail. If Exchange Server's internet send connector uses the gateway as a smart host, change it before you decommission. Either relay through Exchange Online, with your tenant's MX value as the smart host and a certificate whose name matches
TlsSenderCertificateNameon the OnPremises inbound connector, or deliver through DNS and add the server's public IP address to SPF. A connector that doesn't match produces550 5.7.64 TenantAttribution; Relay Access Denied; for the certificate case, Microsoft's fix is to import any missing intermediate CA certificates on the sending server. - Recipients that live only on-premises. Synchronize mail-enabled public folders with Microsoft's sync script (see migrating public folders), give on-premises dynamic distribution groups a mail contact in Exchange Online, and allow up to 24 hours for on-premises changes to reach Directory-Based Edge Blocking.
- Hybrid connectors. Run the Hybrid Configuration Wizard again instead of editing them by hand; my hybrid mail flow deep dive explains each one.
- Server versions. Exchange Server 2016 and 2019 reached end of support on 14 October 2025; Exchange Server Subscription Edition (SE) is current. Keep that upgrade, or removing the last server, out of this project (see every Exchange Online migration scenario).
# Exchange Management Shell: which send connectors still point at the gateway?
Get-SendConnector | Format-List Name, AddressSpaces, SmartHosts, RequireTLS, TlsCertificateNameTo verify, trace an internet message to an on-premises mailbox. Good looks like a delivery over the hybrid outbound connector with no Defer events; a 4.4.316 (connection refused) or 4.4.317 (certificate chain) deferral points at the firewall or the certificate. Cross-premises test messages should still show X-MS-Exchange-Organization-AuthAs: Internal.
Apps, devices and services that send mail#
Gateways often relay for printers, line-of-business apps and on-premises servers, and they can hide SaaS platforms that send as your domain. Find them in the gateway's relay rules and logs before cutover, then move each one to a supported method:
- SMTP AUTH client submission to
smtp.office365.comon port 587 for anything that can authenticate, ideally with OAuth. Basic authentication for SMTP AUTH is being retired; my SMTP AUTH and relay guide has the current timeline and Microsoft's recommended alternatives. - SMTP relay through an OnPremises inbound connector that matches the device's certificate or static public IP address, sending to your MX endpoint on port 25.
- Direct Send for internal recipients only, and only as a last resort.
Microsoft notes that relaying through Microsoft 365 isn't meant for marketing mail or anything recipients could see as spam. With the connector restriction gone, anyone can attempt Direct Send, meaning anonymous mail from your own domains to your mailboxes, which a Partner connector restricted for sender domain * used to reject. When nothing legitimate depends on it, block it:
Get-OrganizationConfig | Format-List RejectDirectSend
Set-OrganizationConfig -RejectDirectSend $trueDirect Send messages are then rejected as shown below, and Microsoft's announcement says each approved sender needs a Partner connector that authenticates its source:
550 5.7.68 TenantInboundAttribution; Direct Send not allowed for this organization from unauthorized sourcesAlso check SaaS platforms that email your own users from your domain. The gateway may have allowed them, and now they meet spoof intelligence directly, so fix their SPF or DKIM alignment or add a spoof allow entry. Good looks like Get-MessageTraceV2 -SenderAddress showing Delivered for each sender, not Quarantined or FilteredAsSpam.
Decommission the gateway#
Wait until the rollback window has closed and the gateway has delivered nothing for an agreed period, such as a week:
$gatewayIPs = "203.0.113.10","203.0.113.11" # every public IP the gateway delivers from
foreach ($ip in $gatewayIPs) {
$n = @(Get-MessageTraceV2 -FromIP $ip -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) -ResultSize 5000).Count
"{0}: {1} messages in the last 7 days" -f $ip, $n
}- Export the configuration, logs, quarantine and archive data you still need before access ends with the contract.
- Connectors and rules. Disable the gateway's inbound connector, wait a quiet week, then remove it along with the outbound connector, the SCL -1 rule and any rule that tests for the gateway's headers or IP addresses.
- Exceptions. Remove the gateway's addresses from the connection filter policy, Tenant Allow/Block List entries created for it, its trusted ARC sealer (
Set-ArcConfigreplaces the whole list, so keep the other sealers) and Safe Links exclusions for its rewrite domain. - DNS. Remove the gateway from SPF, delete its DKIM selectors, and set MTA-STS back to enforce with only the Microsoft host and a new
id. - Journaling and integrations. Remove journal rules that feed the vendor's archive (see journaling to third-party archives) and the vendor's enterprise applications and API permissions in Microsoft Entra ID.
- On-premises. Remove firewall rules and receive connector remote IP ranges for the gateway, and any send connector that still uses it as a smart host.
- Rewritten links. Ask the vendor how long links it already rewrote in existing mail keep working after the contract ends.
Set-InboundConnector -Identity "From mail gateway" -Enabled $false # first, then wait a quiet week
Remove-InboundConnector -Identity "From mail gateway"
Remove-OutboundConnector -Identity "To mail gateway"
Remove-TransportRule -Identity "Bypass spam filtering - mail from gateway"Good looks like: no connector, rule, allow entry, DNS record or firewall rule mentions the gateway, and your SPF record stays within ten DNS lookups.
Rollback plan#
Agree rollback triggers before cutover day, such as unexplained mail loss or a false-positive rate the business can't accept. Until the rollback window closes, keep everything a rollback needs: the gateway subscription and its old MX values, the low TTL, the SCL -1 rule and outbound connector (disabled, not deleted), the gateway's inbound connector (enabled, without restrictions), and the gateway's SPF include and DKIM selectors.
- Point the MX record back to the gateway's values.
- If the gateway should be the only filter again, enable the SCL -1 rule; otherwise keep Microsoft 365 filtering as a second layer.
- If outbound mail had moved, enable the outbound connector again.
- Restore the connector restriction last, once the old TTL has passed and gateway addresses dominate the trace again. Lock it too early and senders that still have the Microsoft MX record cached get 5.7.51.
- Verify:
FromIPshows gateway addresses again, withSFV:SKNin headers if the rule is back on.
# After the MX record points back to the gateway
Enable-TransportRule -Identity "Bypass spam filtering - mail from gateway" # only if the gateway is the sole filter again
Set-OutboundConnector -Identity "To mail gateway" -Enabled $true # only if outbound had moved
# Last, after the old TTL has passed
Set-InboundConnector -Identity "From mail gateway" -RestrictDomainsToIPAddresses $trueIf it goes wrong#
| Symptom | Likely cause | Fix |
|---|---|---|
Senders get 550 5.7.51 TenantInboundAttribution | Partner connector restriction still on | Cutover step 2 |
Senders get 550 5.4.1 Recipient address rejected: Access denied. AS(201806281) | Recipient missing from the directory on an Authoritative domain | Create or sync the recipient; see the 5.4.1 guide |
| Notifications from a SaaS platform land in Junk Email or quarantine as spoofing | The sender fails SPF or DKIM alignment for your domain, and the gateway used to allow it | Fix its authentication or add a spoof allow entry |
| Mail to on-premises mailboxes stays Pending | Firewall, receive connector or certificate between Exchange Online and Exchange Server | Read the Defer event in the trace details |
Apps relaying through Microsoft 365 get 550 5.7.64 TenantAttribution; Relay Access Denied | The connector doesn't match the app's IP address or certificate | Fix the match or the certificate chain |
Apps get 550 5.7.68 TenantInboundAttribution | RejectDirectSend is on and the sender isn't attributed to a connector | Give it a connector or SMTP AUTH |
External recipients see dkim=none | DKIM signing isn't enabled for the domain | Phase 5, step 2 |
| Links wrapped twice or broken | The gateway still rewrites links somewhere | Turn off its wrapping or exclude its domain in Safe Links |
| "My email disappeared" tickets | Users check the old digest, not Microsoft's quarantine or Junk Email folder | Quarantine notifications and a short user guide |
Tips & gotchas#
- PowerShell message trace times are in UTC, and each
Get-MessageTraceV2query covers at most 10 days; my message trace guide has the details. - Cloud gateways share IP addresses among many customers, so never leave those addresses in an allow list after the move.
- For codes this guide doesn't cover, keep my Exchange Online NDR quick reference open on cutover day.

