Exchange Online mail flow rules (transport rules) inspect every message in transit and act on it before it reaches a mailbox, which makes them the right tool for organization-wide disclaimers, external sender warnings and blocking unwanted attachments. You build them in the Exchange admin center under Mail flow > Rules or with New-TransportRule in Exchange Online PowerShell, test them in audit mode, then switch them to Enforce. This guide walks through three production-ready rules and the settings that decide whether they behave as you expect.
Who this guide is for and what you will have
This guide is for Microsoft 365 and Exchange administrators who need consistent, tenant-wide message handling that does not depend on users configuring Outlook. By the end you will have:
- An outbound legal disclaimer that is added once per conversation, not on every reply.
- An external sender warning, either the native Outlook External tag, a body banner, or both.
- A rule that rejects messages carrying attachment types you do not accept, with a clear non-delivery report (NDR) for the sender.
- A repeatable way to test rules, check their order and confirm what they did using message trace.
If you are moving mail into Exchange Online at the same time, build these rules before the cutover so that the first messages that flow through the tenant are already handled. The IMAP to Exchange Online migration guide and the Google Workspace to Microsoft 365 migration guide cover the migration side.
How mail flow rules work
Every rule is built from four parts:
| Component | What it does | How multiple entries combine |
|---|---|---|
| Conditions | Identify the messages the rule applies to | Multiple conditions use AND; multiple values inside one condition use OR |
| Exceptions | Exclude messages from the rule | Multiple exceptions use OR, so matching any one exception skips the rule |
| Actions | What happens to matching messages | All actions in the rule are applied |
| Properties | Priority, mode, dates, severity, stop processing | Set once per rule |
A few behaviours matter for every rule you write:
- A rule with no conditions applies to every message. Microsoft's documentation warns that removing all conditions from a delete or reject rule would act on all inbound and outbound mail for the organization.
- Priority decides the order. The rule at the top of the Rules page has priority 0 and runs first. In PowerShell you set the
Prioritynumber directly. - Stop processing more rules prevents any later rule from acting on a message once this rule matches. It is stored as the
StopRuleProcessingaction. - Match sender address in message (
SenderAddressLocation) decides whether sender conditions look at the message header (the From field, the default), the SMTP envelope, or both. - System messages are not processed. NDRs generated by Exchange, journal reports and messages to arbitration mailboxes skip mail flow rules.
- There is no history. Exchange Online does not keep previous versions of a rule, so export your rules before major changes.
Two ways of creating rules also differ in one important default. Rules created in the new EAC start disabled so you can review them, while New-TransportRule creates rules enabled unless you pass -Enabled $false.
Prerequisites
- Membership in the Organization Management role group in Exchange Online, which the Feature permissions article lists for the "Mail flow rules" feature. Message trace can also be run by members of Compliance Management and Help Desk.
- The Exchange Online PowerShell module (ExchangeOnlineManagement) if you want to script the rules.
- At least one internal and one external mailbox you can send test messages from.
Connect to Exchange Online PowerShell:
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName admin@contoso.comBefore you change anything, back up the existing rule collection. Export-TransportRuleCollection returns the rules as XML data that you write to a file:
$file = Export-TransportRuleCollection
[System.IO.File]::WriteAllBytes('C:\MailFlowRules\Backup-2026-10-11.xml', $file.FileData)Then list what already exists, in processing order:
Get-TransportRule | Format-Table Name,State,Priority,ModeRule 1: Outbound disclaimer added once per conversation
Build it in the EAC
- Open the new EAC at
https://admin.exchange.microsoft.comand go to Mail flow > Rules. - Select Add a rule > Apply disclaimers.
- On Set rule conditions, give the rule a unique name, such as
Outbound disclaimer. - Under Apply this rule if, select The recipient > is external/internal, choose Outside the organization and select Save. Without this condition, the disclaimer is also added to internal and inbound mail, because rules apply to all directions by default.
- Under Do the following, keep Apply a disclaimer to the message with append a disclaimer (or choose prepend a disclaimer to put it at the top). Select Enter text and paste the disclaimer.
- Select Select one to choose the fallback action (covered below).
- Under Except if, select The subject or body > Subject or body includes any of these words and enter a distinctive phrase from your disclaimer (this is the
ExceptIfSubjectOrBodyContainsWordsexception used in the PowerShell version below; Subject or body matches these text patterns also works but evaluates regular expressions). This stops the disclaimer from being stamped again on replies and forwards that already contain it. - On Set rule settings, choose Test without Policy Tips for now, and leave Match sender address in message on Header.
- Select Next, review, and select Finish. Then open the rule and turn on Enable or disable rule.
Disclaimer text can include HTML, inline CSS and images through the IMG tag, and it supports tokens filled from the sender's directory attributes, such as %%DisplayName%%, %%Title%%, %%Department%%, %%Phone%%, %%Company%% and %%WindowsEmailAddress%%. That makes it possible to build a simple, consistent signature block as well as a legal notice. The maximum length of the disclaimer text is 5,000 characters.
Build it in PowerShell
The same rule in PowerShell, created in audit mode so it does not modify mail yet:
$disclaimer = @"
<p><b>%%DisplayName%%</b> | %%Title%% | Contoso Ltd</p>
<p>This email and any attachments are confidential and intended only for the named recipient.
If you received it in error, notify the sender and delete it.</p>
"@
New-TransportRule -Name "Outbound disclaimer" `
-SentToScope NotInOrganization `
-ApplyHtmlDisclaimerLocation Append `
-ApplyHtmlDisclaimerText $disclaimer `
-ApplyHtmlDisclaimerFallbackAction Ignore `
-ExceptIfSubjectOrBodyContainsWords "intended only for the named recipient" `
-Mode AuditThe exception value can be at most 128 characters and must not have leading or trailing spaces.
Choose the fallback action deliberately
If a rule cannot change the message body, for example because the message is encrypted or signed, the fallback action decides what happens:
| Fallback | Result | When to use it |
|---|---|---|
| Wrap (default) | A new message carrying the disclaimer is created and the original is attached to it | Only when the disclaimer is mandatory and recipients can handle a wrapped message |
| Ignore | The original message is delivered without the disclaimer | Most outbound disclaimers, so encrypted mail still arrives normally |
| Reject | The original message is returned to the sender in an NDR | When nothing may leave without the disclaimer |
Wrap has two side effects. Later rules that inspect the subject or body see the wrapper, not the original, so put content-inspection rules before the disclaimer rule. And if wrapping fails, the original message is returned to the sender. Microsoft also states that you should not use Wrap in rules that affect incoming messages from external senders, because it interferes with Safe Attachments scanning. This command finds any rules with that problem:
Get-TransportRule | where {$_.ApplyHTMLDisclaimerFallbackAction -eq 'Wrap' -and $_.FromScope -eq 'NotInOrganization'}Rule 2: Mark messages from external senders
You have two mechanisms, and they solve slightly different problems.
Option A: the native External tag in Outlook
Set-ExternalInOutlook turns on external sender identification in Outlook, Outlook for Mac, Outlook on the web and Outlook for iOS and Android. An External icon appears near the subject line of messages from external senders, and the message itself is not changed.
Set-ExternalInOutlook -Enabled $trueExempt trusted partners by address, domain or a domain with all its subdomains. The allow list is checked against the 5322.From address, is limited to 200 entries and 8 KB in total, and supports add and remove without overwriting existing entries:
Set-ExternalInOutlook -AllowList @{Add="fabrikam.com","*.fabrikam.com"; Remove="old-partner@fabrikam.com"}After you enable it, users can take 24 to 48 hours to see the icon. If you already prepend text to the subject of external mail with a transport rule, Microsoft advises disabling that rule before you enable this feature, otherwise users see both.
Option B: a banner rule
A banner added as a prepended disclaimer is visible in every client, including mail apps that do not support the native tag. Build it like the disclaimer, but scope it to inbound external mail:
$banner = @"
<table border="1" cellpadding="6" bgcolor="#FFF4CE"><tr><td>
<b>External sender.</b> This message came from outside Contoso. Do not open links or attachments unless you expect them.
</td></tr></table>
"@
New-TransportRule -Name "External sender banner" `
-FromScope NotInOrganization `
-SentToScope InOrganization `
-ApplyHtmlDisclaimerLocation Prepend `
-ApplyHtmlDisclaimerText $banner `
-ApplyHtmlDisclaimerFallbackAction Ignore `
-ExceptIfSubjectOrBodyContainsWords "This message came from outside Contoso" `
-Mode AuditNote the fallback. Because this rule acts on inbound external mail, Wrap must not be used. Microsoft's guidance is to use Reject instead of Wrap here; Ignore is the other valid choice and delivers signed or encrypted messages without the banner rather than bouncing them. Pick the one that matches your policy, and understand that the exception phrase can be included by an external sender to suppress the banner.
If you also want a subject prefix, add -PrependSubject "[External] " to the rule. Microsoft suggests ending the value with a space (or a colon and a space) so it does not run into the original subject. Remember that Microsoft advises disabling subject-tagging rules before you turn on the native External tag, so pick one approach for the subject line.
FromScope NotInOrganization matches senders whose address is not in one of your accepted domains (or is in an external relay domain). Senders that forge one of your own accepted domains are not matched by this condition, so do not rely on the banner to flag spoofed internal addresses.
Rule 3: Block attachment types you do not accept
Anti-malware policies can already block specific file types through the common attachment types filter, so check that first. A mail flow rule is useful when you need a custom NDR, a time-limited block, or different handling for specific senders or recipients.
Reject by file extension
In the EAC, create a rule with Create a new rule, set Apply this rule if to Any attachment > File extension includes these words, add each extension, and set Do the following to Block the message > Reject the message and include an explanation. In PowerShell:
New-TransportRule -Name "Reject disk image attachments" `
-AttachmentExtensionMatchesWords iso,img,vhd,vhdx `
-RejectMessageReasonText "Contoso does not accept disk image attachments. Share the file through a link instead." `
-StopRuleProcessing $true `
-Mode AuditThe extensions here are an example; use the list your security policy defines. Nested attachment extensions, meaning files inside the original attachments, are also inspected. When you set a rejection reason without a status code, the NDR uses enhanced status code 5.7.1. If you need your own code, RejectMessageEnhancedStatusCode accepts 5.7.1 or a value from 5.7.900 to 5.7.999. In Exchange Online the reason text can be up to 1,024 characters.
Silently drop executables
AttachmentHasExecutableContent inspects file properties instead of trusting the extension, so a renamed executable is still caught. This is Microsoft's own example:
New-TransportRule -Name "Block Executable Attachments" -AttachmentHasExecutableContent $true -DeleteMessage $trueDeleteMessage drops the message without an NDR. Use it only when you are sure nobody needs to know the message was stopped; otherwise reject with a reason so senders can correct course.
Time-limited blocks
During an outbreak you can activate a rule for a fixed window with Activate this rule on and Deactivate this rule on in the EAC, or -ActivationDate and -ExpiryDate in PowerShell. Outside the window the rule stays enabled but is not processed.
Test, order and enforce
- Wait 30 minutes after creating or changing a rule before you test. Testing earlier gives inconsistent results.
- Send test messages that should match and that should not match: internal to external, external to internal, replies, forwards, and messages that could hit more than one rule.
- Check message trace. In the EAC go to Mail flow > Message trace, select Start a trace, find the test message and open it. Look for the Transport rule event and the action recorded. In PowerShell, pipe a trace into the detail cmdlet:
Get-MessageTraceV2 -SenderAddress admin@contoso.com -StartDate (Get-Date).AddHours(-2) -EndDate (Get-Date) | Get-MessageTraceDetailV2- Set the order. Content-inspection and blocking rules should run before any disclaimer rule that might wrap messages:
Set-TransportRule -Identity "Reject disk image attachments" -Priority 0
Get-TransportRule | Format-List Name,Priority- Enforce. When the results look right, switch the mode:
Set-TransportRule -Identity "Outbound disclaimer" -Mode EnforceIn the EAC, test modes are labelled Test without Policy Tips (PowerShell Audit) and Test with Policy Tips (AuditAndNotify). For longer-term monitoring, the Exchange Transport Rule report under Reports > Mail flow counts rule matches for every rule whose severity is not Not audit. Most data appears within 24 hours, but some can take up to five days.
Troubleshooting
The rule is enabled but nothing happens. Check that 30 minutes have passed, then check priority: an earlier rule with Stop processing more rules, or one that quarantines the message, prevents later rules from running. Moving the rule temporarily to priority 0 is a quick test.
A condition on a distribution group never matches. SentTo matches mailboxes, mail users and contacts, not distribution groups. Use is a member of this group (SentToMemberOf) instead.
The disclaimer appears on every reply. Add or fix the exception that looks for a unique phrase in the disclaimer, and make sure the phrase is short enough (128 characters maximum) and exactly as it appears in the text.
Two conditions are both required, but you wanted either. Conditions in one rule are combined with AND. Duplicate the rule in the EAC and keep one condition in each copy.
Encrypted or signed messages arrive wrapped as attachments. The disclaimer's fallback action is Wrap. Change it to Ignore or Reject according to your policy.
Senders receive "550 5.7.128 TRANSPORT.RULES.RejectMessage; Transport rules loop count exceeded and message rejected". Exchange Online limits transport rules to one redirection per message, and the count is carried across organizations in a message header. If a message that a rule already redirected is redirected again by another rule, for example in a partner organization, it is dropped with this NDR. Remove one of the redirects from the chain.
New rules fail to save or behave unpredictably in a large rule set. Check the limits: 300 rules per organization, 8 KB per rule, and 20 KB for the combined size of all word lists and text patterns in all rules. A transport rule can also add at most 100 recipients to a message and cannot add distribution groups.
Attachment content conditions miss text deep in a file. Rules only inspect a limited amount of text extracted from each attachment (the scanning limit is listed on the Exchange Online limits page), so do not rely on content conditions for very large documents.
Checklist
- Export the rule collection before changes and after you finish.
- Disclaimer rule scoped to external recipients, with an exception for its own text and a deliberate fallback action.
- External sender identification enabled with
Set-ExternalInOutlook, subject-tagging rules disabled, and a banner rule only if non-Outlook clients need it. - No rule with the Wrap fallback that acts on inbound external mail.
- Attachment blocking defined first in the anti-malware policy, with mail flow rules for custom NDRs and exceptions.
- Every new rule tested in Test without Policy Tips mode, verified in message trace, then set to Enforce.
- Blocking rules ordered before disclaimer rules, with Stop processing more rules where appropriate.
- Rule severity set to anything other than Not audit so rules appear in the Exchange Transport Rule report.
References
- Mail flow rules (transport rules) in Exchange Online
- Manage mail flow rules in Exchange Online
- Organization-wide message disclaimers, signatures, footers, or headers in Exchange Online
- Common attachment blocking scenarios for mail flow rules in Exchange Online
- Mail flow rule conditions and exceptions (predicates) in Exchange Online
- Test a mail flow rule in Exchange Online
- New-TransportRule
- Set-ExternalInOutlook
- Message trace in the new EAC in Exchange Online
- Exchange Online limits
- Feature permissions in Exchange Online
- Connect to Exchange Online PowerShell