• Outlook User
  • Exchange Admin
  • Office 365
  • Outlook Developer
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
    • Common Problems
    • Outlook BCM
    • Utilities & Addins

Get Outlook's Internet Headers using VBA

Slipstick Systems

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

Last reviewed on April 22, 2022     43 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, also works in Outlook 2010 and 2007. For Outlook 2003 and older, see Get Internet header VBA code sample for Outlook 2003.

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.

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

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

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

Get Outlook's Internet Headers using VBA was last modified: April 22nd, 2022 by Diane Poremsky
  • Twitter
  • Facebook
  • LinkedIn
  • Reddit
  • Print

Related Posts:

  • View the CC or BCC Addresses in a Sent Message
  • Change the email account on received email
  • Create a custom printout in Outlook
  • Use VBA code sample to view Outlook's Internet Header.
    Get the Internet Header VBA Code Sample for Outlook

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

Tom Geldner (@guest_219702)
September 9, 2022 4:07 pm
#219702

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 (@guest_219230)
April 22, 2022 11:24 am
#219230

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(@diane-poremsky)
Author
Reply to  steve
April 22, 2022 12:11 pm
#219231

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 (@guest_219232)
Reply to  Diane Poremsky
April 22, 2022 12:32 pm
#219232

wow, thanks.
very helpful.

0
0
Reply
Steven (@guest_219233)
Reply to  Diane Poremsky
April 22, 2022 12:41 pm
#219233

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(@diane-poremsky)
Author
Reply to  Steven
April 22, 2022 1:12 pm
#219234

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 (@guest_214197)
October 29, 2019 4:26 pm
#214197

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 (@guest_214196)
October 29, 2019 4:18 pm
#214196

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 (@guest_211879)
September 6, 2018 4:38 am
#211879

Supercallifragilisticexpialidocious
Well done. Thank's a lot!

0
0
Reply
Rajan (@guest_211513)
July 16, 2018 9:38 am
#211513

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 (@guest_211430)
July 2, 2018 4:11 am
#211430

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(@diane-poremsky)
Author
Reply to  Rajan
July 3, 2018 11:22 pm
#211443

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 (@guest_211488)
Reply to  Diane Poremsky
July 11, 2018 5:38 am
#211488

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
Rachana (@guest_210021)
January 19, 2018 6:34 am
#210021

Hi Diane,

I am working on a VB script that converts Outlook mail message to word doc and then save the file as a PDF. The PDF which is being generated is missing the header (which shows the sender's Display Name) .

Could you suggest the way forward. I Have attached my code for reference.

SaveAsPDF Copy.xlsm
0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Rachana
January 20, 2018 9:17 am
#210049

I haven't run your code yet, but the macro at https://www.slipstick.com/developer/code-samples/save-outlook-email-pdf/ created a pdf with the header you see in printouts (or replies) - with the sender in this format:
From: OutlookForums
I'll test your code when i get a chance (I'm on 'the road' right now.)

0
0
Reply

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

Latest EMO: Vol. 28 Issue 22

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?

Subscribe to Exchange Messaging Outlook






Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • WeekMonthAll
  • How to Remove the Primary Account from Outlook
  • Adjusting Outlook's Zoom Setting in Email
  • Outlook: Web Bugs & Blocked HTML Images
  • Save Sent Items in Shared Mailbox Sent Items folder
  • Move an Outlook Personal Folders .pst File
  • Create rules that apply to an entire domain
  • Use PowerShell to get a list of Distribution Group members
  • View Shared Calendar Category Colors
  • How to Create a Pick-a-Meeting Request
  • Remove a password from an Outlook *.pst File
  • Send Individual Messages when Sending Bulk Email
  • Centrally managed signatures in Office 365?
  • Create a rule to delete spam with no sender address
  • Open Outlook Folders using PowerShell or VBScript
  • Cannot add Recipients in To, CC, BCC fields on MacOS
  • Change Appointment Reminder Sounds
  • Messages appear duplicated in message list
  • Reset the New Outlook Profile
  • Delete Old Calendar Events using VBA
  • Use PowerShell or VBA to get Outlook folder creation date
Ajax spinner

Newest Code Samples

Delete Old Calendar Events using VBA

Use PowerShell or VBA to get Outlook folder creation date

Rename Outlook Attachments

Format Images in Outlook Email

Set Outlook Online or Offline using VBScript or PowerShell

List snoozed reminders and snooze-times

Search your Contacts using PowerShell

Filter mail when you are not the only recipient

Add Contact Information to a Task

Process Mail that was Auto Forwarded by a Rule

Recent Bugs List

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

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

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.

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

Other Microsoft 365 applications and services




Windows 10 Issues

  • iCloud, Outlook 2016, and Windows 10
  • Outlook Links Won’t Open In Windows 10
  • Outlook can’t send mail in Windows 10: error Ox800CCC13
  • Missing Outlook data files after upgrading Windows?

Outlook Top Issues

  • The Windows Store Outlook App
  • The Signature or Stationery and Fonts button doesn’t work
  • Outlook’s New Account Setup Wizard
  • Outlook 2016: No BCM
  • Exchange Account Set-up Missing in Outlook 2016

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

Contact Tools

Data Entry and Updating

Duplicate Checkers

Phone Number Updates

Contact Management Tools

Diane Poremsky [Outlook MVP]

Make a donation

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

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

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 | Advertise | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2023 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