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

Get Outlook's Internet Headers using VBA or PowerShell

Slipstick Systems

› Developer › Code Samples › Get Outlook’s Internet Headers using VBA or PowerShell

Last reviewed on November 25, 2024     45 Comments

Use this code sample and function to display the Internet header of selected message in a new message form.

Read Internet Header

Tested in Outlook 2013, 2019, 2021, and Outlook 365, also works in Outlook 2010 and 2007.

The PowerShell version does not require you to change Outlook security settings. to use, select one or more messages then run the script.

clear

$olApp = new-object -comobject outlook.application
$PropName = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"

$olFolder = ($olApp.ActiveExplorer())
$Selection = $olFolder.Selection

foreach ($olMsg in $Selection) {
$oPA = $olMsg.PropertyAccessor
$value = $oPA.GetProperty($PropName)

$Mail = $olApp.CreateItem(0)
$ndatetime = Get-Date -Format g
$Mail.Subject = $olMsg.subject + ' ' +$ndatetime 
$Mail.Body = $value
$Mail.display()
}

Save it as a *.ps1 then right-click and choose Run with PowerShell.

Or create a shortcut and pin it to the taskbar or Start menu. The target will be
powershell.exe -file "C:\path\to\filename.ps1"

Note: Windows will add the full path to powershell.exe to the shortcut.
Create a shortcut to run the powershell script

 

VBA method to get message header

Sub ViewInternetHeader()
    Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
    Dim strheader As String

    For Each olItem In Application.ActiveExplorer.Selection
        strheader = GetInetHeaders(olItem)
    
        Set olMsg = Application.CreateItem(olMailItem)
        With olMsg 
            .BodyFormat = olFormatPlain
            .Body = strheader
            .Display
        End With
    Next
    Set olMsg = Nothing
End Sub

Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
    ' Purpose: Returns the internet headers of a message.'
    ' Written: 4/28/2009'
    ' Author:  BlueDevilFan'
    ' //techniclee.wordpress.com/
    ' Outlook: 2007'
    Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
    Dim olkPA As Outlook.PropertyAccessor
    Set olkPA = olkMsg.PropertyAccessor
    GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
    Set olkPA = Nothing
End Function

Write the header to a text file

This version of the above macro writes the header to a text file and opens it in Notepad. (You'll need the Function GetInetHeaders from above).

If you want to open it in another Text application, replace "notepad " with the file path and name, making sure to leave the space after the filename.

  Sub ViewInternetHeader()
    Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
    Dim strheader As String

    For Each olItem In Application.ActiveExplorer.Selection
        strheader = GetInetHeaders(olItem)
    
' ### write to a text file
Dim FSO As Object
Dim strFile As String
Dim strFolderpath As String

Set FSO = CreateObject("Scripting.FileSystemObject")

' save to documents
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    strFile = strFolderpath & "\header.txt"
Set objFile = FSO.CreateTextFile(strFile, True) ' True overwrites the file
Debug.Print strFile

    objFile.Write "" & strheader
    objFile.Close
     
 Call Shell("notepad.exe " & strFile, vbNormalFocus)
  
' ### end write to text file
       
    Next
    Set olMsg = Nothing
End Sub

 

Get Specific Values from the header

But combining RegEx and the macro above we can get specific values out of the header. In this example, we're getting the address in the Return-Path.

If you need two or more values, you'll use a Case statement to loop through the header. See Get two (or more) values from a message for an example.

Sub GetValuesFromInternetHeader()
    Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
    Dim strHeader As String
    Dim strResult As String
    Dim strResults As String
    Dim Reg1 As Object
    Dim M1 As Object
    Dim M As Object
 
    For Each olItem In Application.ActiveExplorer.Selection
        strHeader = GetInetHeaders(olItem)
    
      Set Reg1 = CreateObject("VBScript.RegExp")
    With Reg1
        .Pattern = "(Return-Path:\s(.*))"
        .Global = True
    End With
    
    If Reg1.test(strHeader) Then
    
        Set M1 = Reg1.Execute(strHeader)
        For Each M In M1
' 0 = everything in the first set of ()
' 1 = everything in the second set of ()
        Debug.Print M.SubMatches(0)
        strResult = M.SubMatches(1)

' do something with the result
        strResults = strResult & vbCrLf & vbCrLf & strResults
        Next
    End If
    
    Next

        Set olMsg = Application.CreateItem(olMailItem)
        With olMsg
            .BodyFormat = olFormatPlain
            .Body = strResults
            .Display
        End With
    Set olMsg = Nothing
End Sub

Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
    ' Purpose: Returns the internet headers of a message.'
    ' Written: 4/28/2009'
    ' Author:  BlueDevilFan'
    ' //techniclee.wordpress.com/
    ' Outlook: 2007'
    Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
    Dim olkPA As Outlook.propertyAccessor
    Set olkPA = olkMsg.propertyAccessor
    GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
    Set olkPA = Nothing
End Function

 

Send a Spam Report

If you need to send a spam report to your ISP, you can use a macro to automate it. This macro will work on one message or a selection of messages.

If the macro is not creating a body that can be processed by the reporting service, try changing the 0x007D001E value to 0x007D001F. This returns PR_TRANSPORT_MESSAGE_HEADERS_W instead of PR_TRANSPORT_MESSAGE_HEADERS. See Geldner's thread and answer here: Problem submitting SPAM using Outlook VBA Form

Sub ForwardSpam()
    Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
    Dim strHeader As String
    Dim strFWHeader As String
    Dim strNote As String

    For Each olItem In Application.ActiveExplorer.Selection
        strHeader = GetInetHeaders(olItem)

    strNote = "boilerplate note, if needed"
        
      Set olMsg = olItem.Forward
       With olMsg
        .To = "report@address.com"
        .BodyFormat = olFormatPlain
        .Body = strNote & vbCrLf & vbCrLf & strHeader & vbCrLf & vbCrLf & olItem.Body
        .Display ' change to .send when satisfied
       End With
    olItem.Delete
  Next
    Set olMsg = Nothing
End Sub

Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
    ' Purpose: Returns the internet headers of a message.'
    ' Written: 4/28/2009'
    ' Author:  BlueDevilFan'
    ' //techniclee.wordpress.com/
    ' Outlook: 2007'
    Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
    Dim olkPA As Outlook.propertyAccessor
    Set olkPA = olkMsg.propertyAccessor
    GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
    Set olkPA = Nothing
End Function

 

Using PowerShell Scripts

To use PowerShell scripts with Outlook, start typing PowerShell on the start menu and open Windows PowerShell when it comes up. Windows PowerShell ISE has a script pane at the top, which is useful if you want to edit the script.

Paste the entire script in the PowerShell window and press Enter or the Run button if using PowerShell ISE.
bulk change contact fields

PowerShell ise

Note: PowerShell scripts will not work with new Outlook or Outlook on the web.

Saving PowerShell Scripts

If you want to save the script as a .ps1 file, paste it into Notepad and save it with the extension .ps1. To open it in the PowerShell IDE, type PowerShell on the start menu and click on Windows PowerShell IDE when the PowerShell app is found. Paste the script in the editing window.

To use it, you need to allow local scripts by running this command:

Set-ExecutionPolicy RemoteSigned

To run your saved .ps1 file, right-click on the script and choose Run with PowerShell.

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

More Information

Retrieving Internet Headers Using VBA in Outlook 2007/2010 Includes a code sample to use with Run a Script rule.

For Outlook 2003 and older, see Get Internet header VBA code sample for Outlook 2003.

Get Outlook's Internet Headers using VBA or PowerShell was last modified: November 25th, 2024 by Diane Poremsky

Related Posts:

  • View the CC or BCC Addresses in a Sent Message
  • Use VBA code sample to view Outlook's Internet Header.
    Get the Internet Header VBA Code Sample for Outlook
  • Use an Outlook Macro to Send Files by Email
  • Change the email account on received email

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
45 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

Frederic
September 22, 2024 1:09 pm

It would be nice to be able to get a specific part of the Internet Headers, for instance the Reply-To adress, and to display it in a new column (custom view). Very useful against spoofing ! I have tried to design a custom form for this purpose... but to no avail...

0
0
Reply
Diane Poremsky
Author
Reply to  Frederic
September 23, 2024 12:30 am

That is possible, using propertyaccessor or regex to find a value in the header.
https://www.slipstick.com/developer/read-mapi-properties-exposed-outlooks-object-model/

https://www.slipstick.com/developer/code-samples/outlooks-internet-headers/#values
use .Pattern = "(Reply-To:\s(.*))"

0
0
Reply
Tom Geldner
September 9, 2022 4:07 pm

Is there an easy way to mod the Spam Report macro so that it strips any blank lines from the header when creating the email report? Outlook, for some reason, often creates blank lines in headers and it causes SPAMCOP.NET to choke.

0
0
Reply
steve
April 22, 2022 11:24 am

this is excellent.
How do I create a text file with the exact same information as the email that the 1st macro made?

0
0
Reply
Diane Poremsky
Author
Reply to  steve
April 22, 2022 12:11 pm

Use this in place of the code that creates a message in the first macro

' ### write to a text file
Dim FSO As Object
Dim strFile As String
Dim strFolderpath As String

Set FSO = CreateObject("Scripting.FileSystemObject")

' save to documents
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    strFile = strFolderpath & "\header.txt"
Set objFile = FSO.CreateTextFile(strFile, True) ' use False if you don't want to overwrite
Debug.Print strFile

    objFile.Write "" & strheader
    objFile.Close
 
 Call Shell("notepad.exe " & strFile, vbNormalFocus)
  
' ### end write to text file

1
0
Reply
Steven
Reply to  Diane Poremsky
April 22, 2022 12:32 pm

wow, thanks.
very helpful.

0
0
Reply
Steven
Reply to  Diane Poremsky
April 22, 2022 12:41 pm

So much information! Wow.
Is there any way to filter the header and only write the date/time received to the text file? Is there a way to break out each piece of information, like recipient?, sender?
Are all of these 'Objects'?

0
0
Reply
Diane Poremsky
Author
Reply to  Steven
April 22, 2022 1:12 pm

You can get anything out of the header using regex, but the common fields are in vba - receivedtime, subject, sendername and senderemailaddress, recipient all are stored in fields accessible by VBA.
Get the fields, then write the strings to the text file.
With olItem
strName = .SenderName
strSender = .SenderEmailAddress
strTime = .ReceivedTime
End With

0
0
Reply
SteveB
October 29, 2019 4:26 pm

I just figured out that it'll work..... just not with a user form.
Would you be willing to modify it to work with a user form, or to put an output into a user form/label on a form?

0
0
Reply
Steve Buckley
October 29, 2019 4:18 pm

Hi.
In trying the code for the first one above, I get a run time error on the
.display under the With operation.
It tells me that it cannot perform that operation because a dialogue box is open, and needs to be closed. I have two dialogues open.
1- the program itself.
2- the user form I've created. I close the user form, and it still throws the error.

With olMsg 
            .BodyFormat = olFormatPlain
            .Body = strheader
            .Display
        End With

I'm using office 365.
Thank you.

0
0
Reply
Rainer
September 6, 2018 4:38 am

Supercallifragilisticexpialidocious
Well done. Thank's a lot!

0
0
Reply
Rajan
July 16, 2018 9:38 am

Dear Diane,
Thanks for your code . would you please me , i want to add some condition to code after extraction of few details. such as ; Reply To; From; To; and etc.
please help me to add some condition on it.

Thanks in advance.

0
0
Reply
Rajan
July 2, 2018 4:11 am

Dear Diane,
Thanks for your code . it was really helpful to me . in the email headers i was trying to remove particular line from every header.

"h=sender:from:reply-to:to:subject:mime-version:content-type:list-unsubscribe:x-report-abuse:form-sub;"

please help me to find solution on this .

0
0
Reply
Diane Poremsky
Author
Reply to  Rajan
July 3, 2018 11:22 pm

you'll change the pattern to find it...
.Pattern = "(h=(.*)-sub)"

Do you actually need to remove it from the header or need to copy it out of the header? VBA can't edit the internet header - you may be able to use Redemption (outlookspy.com) to edit it but i don't have code samples. If the line nver changes, you can use the replace function to remove it.

0
0
Reply
Rajan
Reply to  Diane Poremsky
July 11, 2018 5:38 am

Dear Diane,
Thanks for response,
From the header i am extracting few details , such as;

.Pattern = "(To:\s(.*))"

but in result i am getting this , as both Contains To: ,
can u help to get exact match of string what i am searching . as code is not understanding that i am looking only for "To" not
"Reply-to."

Reply-To: Jon Luchette
To: Ernie Bourassa

0
0
Reply

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

Latest EMO: Vol. 30 Issue 36

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
  • Use Classic Outlook, not New Outlook
  • How to Remove the Primary Account from Outlook
  • Reset the New Outlook Profile
  • This operation has been cancelled due to restrictions
  • Adjusting Outlook's Zoom Setting in Email
  • How to Hide or Delete Outlook's Default Folders
  • Disable "Always ask before opening" Dialog
  • Removing Suggested Accounts in New Outlook
  • Remove a password from an Outlook *.pst File
  • Syncing Outlook with an Android smartphone
  • Opt out of Microsoft 365 Companion Apps
  • Mail Templates in Outlook for Windows (and Web)
  • Urban legend: Microsoft Deletes Old Outlook.com Messages
  • Buttons in the New Message Notifications
  • Move Deleted Items to Another Folder Automatically
  • 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
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

Opt out of Microsoft 365 Companion Apps

Mail Templates in Outlook for Windows (and Web)

Urban legend: Microsoft Deletes Old Outlook.com Messages

Buttons in the New Message Notifications

Move Deleted Items to Another Folder Automatically

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

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.

:wpds_smile::wpds_grin::wpds_wink::wpds_mrgreen::wpds_neutral::wpds_twisted::wpds_arrow::wpds_shock::wpds_unamused::wpds_cool::wpds_evil::wpds_oops::wpds_razz::wpds_roll::wpds_cry::wpds_eek::wpds_lol::wpds_mad::wpds_sad::wpds_exclamation::wpds_question::wpds_idea::wpds_hmm::wpds_beg::wpds_whew::wpds_chuckle::wpds_silly::wpds_envy::wpds_shutmouth:
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