• Outlook User
  • New Outlook app
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
  • Developer
  • Microsoft 365 Admin
    • Common Problems
    • Microsoft 365
    • Outlook BCM
    • Utilities & Addins

Sort messages by Sender domain

Slipstick Systems

› Outlook › Email › Sort messages by Sender domain

Last reviewed on October 8, 2018     28 Comments

A security update disabled the Run a script option in the rules wizard in Outlook 2010 and all newer Outlook versions. See Run-a-Script Rules Missing in Outlook for more information and the registry key to fix restore it.

A user wanted to know how to sort email messages by domain. Although you can filter by domain simply by typing the domain name in the address field, you can't sort as easily.

You can create a custom Formula field using this formula: right([SearchFromEmail],len([SearchFromEmail])-InStr(1,[SearchFromEmail],"@"))
Use a formula to get the domain name

Unfortunately, you can't sort by formula fields. However, custom Text fields are sortable and you can use a macro to add the domain to the custom field.

How to display the sender's email address in Outlook to add the sender's email address field to the view.

To use the first macro, select the messages then run the macro. To add the domain field to messages as they arrive, you'll need to use the run a script rule below.

Macro for selected messages

Public Sub SetDomain()
    ' From http://slipstick.me/1
    Dim currentExplorer As Explorer
    Dim Selection As Selection
    Dim obj As Object
    Dim objProp As Outlook.UserProperty
    Dim strDomain
    
    
    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection

    On Error Resume Next

    For Each obj In Selection
         Set objMail = obj
         
           strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStr(objMail.SenderEmailAddress, "@"))
         Set objProp = objMail.UserProperties.Add("Domain", olText, True)
         objProp.Value = strDomain
        objMail.Save
 
        Err.Clear
    Next
 
    Set currentExplorer = Nothing
    Set obj = Nothing
    Set Selection = Nothing
End Sub

If you use Exchange server, the field will contain the Exchange x.500 address for mail from Internal senders. The easiest fix is to use an if statement to look for an @ sign. No @ sign means it's internal email. You can then enter your domain for these senders or use their alias.

For Each obj In Selection
         Set objMail = obj
         
  Set objProp = objMail.UserProperties.Add("Domain", olText, True)
    If InStr(1, objMail.SenderEmailAddress, "@") > 0 Then
         strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStr(objMail.SenderEmailAddress, "@"))
     Else
        ' strDomain = "yourdomain.com"
        ' use this for the alias - you may need to use /cn in on-prem
         strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStrRev(objMail.SenderEmailAddress, "-"))
    End If

  objProp.Value = strDomain

Create the custom field and add it to your view

To add the custom field to the view follow these steps:

Add a custom Domain field to the view

  1. Close or reduce the size of the reading pane so the From, Subject, Received date and other fields are on one line
  2. Right click on the row of field names and then choose Field Chooser from the menu
  3. Click New and type Domain in the Name field
  4. If User-defined field in [folder] is not visible, select it, then drag the newly created Domain field to the row of field names

Click on the Domain name to sort..

Sort by the domain name

 

Run a script rule

Use the following macro in a run a script rule. If you need instructions, see Outlook's Rules and Alerts: Run a Script.

Public Sub SetDomainScript(Item As Outlook.MailItem)
    ' Fromhttp://slipstick.me/1
    Dim objProp As Outlook.UserProperty
    Dim strDomain
       strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStr(1, objMail.SenderEmailAddress, "@"))
         Set objProp = Item.UserProperties.Add("Domain", olText, True)
         objProp.Value = strDomain
        Item.Save
        
 End Sub

 

Add the Sent To domain

This macro gets the first email address a message is sent to and adds it to the Domain field. You could loop through the entire recipient list and get all addresses or domains, but the list is a simple text list and sorts by the first domain, making it less useful.

This macro works on both incoming messages and messages in your sent folder.

Public Sub SetToDomain()
    ' Fromhttp://slipstick.me/1
    Dim currentExplorer As Explorer
    Dim Selection As Selection
    Dim obj As Object
    Dim objProp As Outlook.UserProperty
    Dim strDomain

 Dim recips As Outlook.Recipients
 Dim recip As Outlook.Recipient
 Dim pa As Outlook.propertyAccessor
 Dim Address As String
 Dim lLen

 Const PR_SMTP_ADDRESS As String = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
    
    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection
 
    On Error Resume Next
 
    For Each obj In Selection
         Set objMail = obj
          
' This gets the first recipient's address
 Set recips = objMail.Recipients
 Set recip = recips.Item(1)
 Set pa = recip.propertyAccessor
  
 Address = LCase(pa.GetProperty(PR_SMTP_ADDRESS))
 lLen = Len(Address) - InStrRev(Address, "@")
          
         strDomain = Right(Address, lLen)
         Set objProp = objMail.UserProperties.Add("Domain", olText, True)
         objProp.Value = strDomain
        objMail.Save
  
        Err.Clear
    Next
  
    Set currentExplorer = Nothing
    Set obj = Nothing
    Set Selection = Nothing
End Sub

 

Create other fields

You can customize the macro to work with other fields. In this example, I'm adding a text field containing the received date formatted in Month day format. Don't forget to use a unique name for the field!

Tip: if you want to sort by a date field, use "yyyy mm dd" for the date format, use olDateTime instead of oltext.

strDomain = Format(objMail.ReceivedTime, "mm/dd/yyyy")
Set objProp = objMail.UserProperties.Add("MyDate", olDateTime, True)

Public Sub SetDate()
    ' Fromhttp://slipstick.me/1
    Dim currentExplorer As Explorer
    Dim Selection As Selection
    Dim obj As Object
    Dim objProp As Outlook.UserProperty
    Dim strDomain
    Dim objMail As MailItem
     
    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection
 
    On Error Resume Next
 
    For Each obj In Selection
         Set objMail = obj
          
   ' make changes here
      strDomain = Format(objMail.ReceivedTime, "MMM dd")
         Set objProp = objMail.UserProperties.Add("MyDate", olText, True)
         objProp.value = strDomain
        objMail.Save
  
        Err.Clear
    Next
  
    Set currentExplorer = Nothing
    Set obj = Nothing
    Set Selection = Nothing
End Sub

To use the macros with other Outlook item types, you only need to change the item type in the Dim statements:
Dim objMail As TaskItem

And the field:
strDomain = Format(objMail.CreationTime, "MMM dd yyyy")

And, of course, you might want to change the field name and type:
Set objProp = objMail.UserProperties.Add("ThisField", olDateTime, True)

Yes, it would be less confusing to use a generic object name, like objItem, but as long as the field is supported by the declared object, it will work.

How to use macros

First: You will need macro security set to low during testing.

To check your macro security in Outlook 2010 or 2013, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.

After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.

Open the VBA Editor by pressing Alt+F11 on your keyboard.

To put the code in a module:

  1. Right click on Project1 and choose Insert > Module
  2. Copy and paste the macro into the new module.

More information as well as screenshots are at How to use the VBA Editor

Sort messages by Sender domain was last modified: October 8th, 2018 by Diane Poremsky

Related Posts:

  • Display the Recipient Email Address in the Sent Items Folder
  • Create a Custom Numbering Field for Outlook messages
  • How to sort the Outlook Calendar by Birthday
  • This macro demonstrates how to pick up the sender's address and use it
    New Message From Sender

About Diane Poremsky

A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Subscribe
Notify of
28 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

erkan (@guest_214892)
March 7, 2020 12:01 pm
#214892

is there any way to make this macro stay there forever and set a shortcut or button?
So if i click that buttom, it should sort according to domain?

0
0
Reply
Rajiv (@guest_211263)
June 10, 2018 3:58 am
#211263

Dear Diane, I added a New Column, named DOMAIN, selected all the messages in my Inbox, around 10000, and ran the macro. First it took ages to populate the Domain field values. Second upon clicking Sort, it simply was not doing it, descending or ascending. Then I noticed, it does some sort of sorting, but could understand it is an extremely slow process. The same process I tried in another mail folder, with 250 messsages, and I was able to sort and group by Domain values. Kindly help me implement the same process for my Inbox, as I really want to clear all the Junk/Useless mails, which are from around 3000 senders, but if I can group them by Domain, it would be a few hundred.

Sorting the messages according to the number of messages based on Domain values, instead of alphabetic sequence, would be the next step, but this can be a secondary goal. Thanks for your kind help.

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Rajiv
November 1, 2018 12:37 am
#212190

Yeah, its definitely a slow macro - it needs to touch every message. I don't believe t can be speeded up. Sorry. (Sorry I missed this earlier).

1
0
Reply
Enrique Nicolas (@guest_207374)
June 26, 2017 12:31 pm
#207374

Hey, i share the method to folder sent.

For Each aObj In Application.ActiveExplorer.Selection
Set oMail = aObj
' This gets the first recipient's address
Set recips = oMail.Recipients
sTmp = recips.Item(1).Address

If InStr(1, sTmp, "@") > 0 Then
sDomain = Right(sTmp, Len(sTmp) - InStr(sTmp, "@"))
Else
If InStr(1, sTmp, "/o=") > 0 Then
sDomain = "att.com"
' use this for the alias - you may need to use /cn in on-prem
nPos = InStr(1, sTmp, "=")
nNext = InStr(nPos + 1, sTmp, "/")
nLen = nNext - nPos
sDomain = Mid(sTmp, nPos + 1, nLen - 1)
Else
sDomain = Right(sTmp, Len(sTmp) - InStrRev(sTmp, "-"))
End If
End If

' sDomain = Right(oMail.SenderEmailAddress, Len(oMail.SenderEmailAddress) - InStr(1, oMail.SenderEmailAddress, "@"))
Set oProp = oMail.UserProperties.Add("NewDomain", olText, True)
oProp.Value = sDomain
oMail.Save
Err.Clear
Next

0
0
Reply
Steve (@guest_206477)
May 10, 2017 7:03 am
#206477

Great tips.

Also see my column formula:
IIf(InStr([SearchFromEmail], "@") = 0, "", Mid([SearchFromEmail], InStr([SearchFromEmail], "@") + 1))

And info here
http://stackoverflow.com/questions/43849213/can-i-add-a-custom-email-domain-column-in-outlook/43889643#43889643

0
0
Reply
Tony (@guest_199010)
May 27, 2016 12:14 pm
#199010

How to remove the field andits contents if the Macro did not work correctly? I run the AddDomain Macro and it worked on the emails coming from outside my company but for the emails that come from inside my company the field added something like this: "/o=company/ou=exchange admin...". I will like to undo what I did until I figure out how to adjust the script. Any ideas?

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Tony
August 25, 2016 10:54 am
#201075

That is normal. On other pages i have examples using left/right functions that get just the alias from the exchange x500 address or you can use an if statement something like

Set objProp = objMail.UserProperties.Add("Domain", olText, True)
If InStr(1, objMail.SenderEmailAddress, "@") > 0 Then
strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStr(objMail.SenderEmailAddress, "@"))
Else
strDomain = "yourdomain.com"
' to get the exchange alias in office 365 exchange online
' strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStrRev(objMail.SenderEmailAddress, "-"))
' or in on-prem
' strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStrRev(objMail.SenderEmailAddress, "/cn"))
End If

objProp.Value = strDomain

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Diane Poremsky
August 25, 2016 11:17 am
#201076

BTW, just changing this line should erase the value from the field -
objProp.Value = "" (it might only work if you do it immediately and won't work if you use the formula method to set the field - you'll need to change the formula or delete the field)

0
0
Reply
Liora (@guest_197484)
March 28, 2016 3:19 am
#197484

Hello,
I have to use the above script on inbox , and use the proprties:
PropTag=PidTagSenderSmtpAddress_W
NmidInteger=0x5D01
In the script there is an object relaited recipient, I need to relait to sender

Thank

0
0
Reply
Badan (@guest_194723)
November 12, 2015 4:30 am
#194723

Thanks, Diane, this is very useful. However, for some reason when I run the script rule this line is not able to extract the domain name:
strDomain = Right(objMail.SenderEmailAddress, Len(objMail.SenderEmailAddress) - InStr(1, objMail.SenderEmailAddress, "@"))

It gives nothing. I added on Error resume next and changed objMail with Item but still this line is not working. What could be the issue?

0
0
Reply
jeanphi (@guest_194108)
October 20, 2015 8:43 am
#194108

I am again. Here's the code. I'm in my .txt file the number of items per sender. But not write in column D (created previously) What is the solution? PS I am not a developer, I try to learn. ----------- ub CombienMailsDate() Dim objOutlook As Object, objnSpace As Object, objFolder As MAPIFolder Dim Sender As Outlook.AddressEntry Dim mail As String Dim myItems As Outlook.Items Dim dict As Object Dim msg As String Dim aObj As Object Dim oProp As Outlook.UserProperty Set objOutlook = CreateObject("Outlook.Application") Set objnSpace = objOutlook.GetNamespace("MAPI") On Error Resume Next Set objFolder = ActiveExplorer.CurrentFolder If Err.Number 0 Then Err.Clear MsgBox "No such folder." Exit Sub End If Set dict = CreateObject("Scripting.Dictionary") Set myItems = objFolder.Items myItems.SetColumns ("SenderEmailAddress") For Each myItem In myItems mail = myItem.SenderEmailAddress If Not dict.Exists(mail) Then End If dict(mail) = CLng(dict(mail)) + 1 Next myItem On Error Resume Next ' Output counts per sender: msg = "" For Each o In dict.Keys msg = msg & o & ": " & dict(o) & " items" & vbCrLf On Error Resume Next For Each aObj In Application.ActiveExplorer.Selection Set oMail = aObj If o = myItem.SenderEmailAddress Then Set oMail = aObj Set oProp = oMail.UserProperties.Add("D", olNumber, True)… Read more »

0
0
Reply

Visit Slipstick Forums.
What's New at Slipstick.com

Latest EMO: Vol. 30 Issue 19

Subscribe to Exchange Messaging Outlook






Support Services

Do you need help setting up Outlook, moving your email to a new computer, migrating or configuring Office 365, or just need some one-on-one assistance?

Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • Week Month All
  • Jetpack plugin with Stats module needs to be enabled.
  • Open Outlook Templates using PowerShell
  • Count and List Folders in Classic Outlook
  • Google Workspace and Outlook with POP Mail
  • Import EML Files into New Outlook
  • Opening PST files in New Outlook
  • New Outlook: Show To, CC, BCC in Replies
  • Insert Word Document into Email using VBA
  • Delete Empty Folders using PowerShell
  • Warn Before Deleting a Contact
  • Classic Outlook is NOT Going Away in 2026
Ajax spinner

Recent Bugs List

Microsoft keeps a running list of issues affecting recently released updates at Fixes or workarounds for recent issues in classic Outlook (Windows).

For new Outlook for Windows: Fixes or workarounds for recent issues in new Outlook for Windows .

Outlook for Mac Recent issues: Fixes or workarounds for recent issues in Outlook for Mac

Outlook.com Recent issues: Fixes or workarounds for recent issues on Outlook.com

Office Update History

Update history for supported Office versions is at Update history for Office

Outlook Suggestions and Feedback

Outlook Feedback covers Outlook as an email client, including Outlook Android, iOS, Mac, and Windows clients, as well as the browser extension (PWA) and Outlook on the web.

Outlook (new) Feedback. Use this for feedback and suggestions for Outlook (new).

Use Outlook.com Feedback for suggestions or feedback about Outlook.com accounts.

Other Microsoft 365 applications and services




New Outlook Articles

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Google Workspace and Outlook with POP Mail

Import EML Files into New Outlook

Opening PST files in New Outlook

New Outlook: Show To, CC, BCC in Replies

Insert Word Document into Email using VBA

Delete Empty Folders using PowerShell

Warn Before Deleting a Contact

Classic Outlook is NOT Going Away in 2026

Newest Code Samples

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Insert Word Document into Email using VBA

Warn Before Deleting a Contact

Use PowerShell to Delete Attachments

Remove RE:, FWD:, and Other Prefixes from Subject Line

Change the Mailing Address Using PowerShell

Categorize @Mentioned Messages

Send an Email When You Open Outlook

Delete Old Calendar Events using VBA

VBA Basics

How to use the VBA Editor

Work with open item or selected item

Working with All Items in a Folder or Selected Items

VBA and non-default Outlook Folders

Backup and save your Outlook VBA macros

Get text using Left, Right, Mid, Len, InStr

Using Arrays in Outlook macros

Use RegEx to extract message text

Paste clipboard contents

Windows Folder Picker

Custom Forms

Designing Microsoft Outlook Forms

Set a custom form as default

Developer Resources

Developer Resources

Developer Tools

VBOffice.net samples

SlovakTech.com

Outlook MVP David Lee

Repair PST

Convert an OST to PST

Repair damaged PST file

Repair large PST File

Remove password from PST

Merge Two Data Files

Sync & Share Outlook Data

  • Share Calendar & Contacts
  • Synchronize two computers
  • Sync Calendar and Contacts Using Outlook.com
  • Sync Outlook & Android Devices
  • Sync Google Calendar with Outlook
  • Access Folders in Other Users Mailboxes

Diane Poremsky [Outlook MVP]

Make a donation

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Productivity

Productivity Tools

Automatic Message Processing Tools

Special Function Automatic Processing Tools

Housekeeping and Message Management

Task Tools

Project and Business Management Tools

Choosing the Folder to Save a Sent Message In

Run Rules on messages after reading

Help & Suggestions

Submit Outlook Feature Requests

Slipstick Support Services

Buy Microsoft 365 Office Software and Services

Visit Slipstick Forums.

What's New at Slipstick.com

Home | Outlook User | Exchange Administrator | Office 365 | Outlook.com | Outlook Developer
Outlook for Mac | Common Problems | Utilities & Addins | Tutorials
Outlook & iCloud Issues | Outlook Apps
EMO Archives | About Slipstick | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2025 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.

wpDiscuz

Sign up for Exchange Messaging Outlook

Our weekly Outlook & Exchange newsletter (bi-weekly during the summer)






Please note: If you subscribed to Exchange Messaging Outlook before August 2019, please re-subscribe.

Never see this message again.

You are going to send email to

Move Comment