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

Use a Macro to Attach Files to New Messages

Slipstick Systems

› Developer › Use a Macro to Attach Files to New Messages

Last reviewed on August 7, 2016     16 Comments

This is a version of the macro at Insert the Newest HTML File. Instead of inserting the file as stationery, it adds the newest file as an attachment to a new message.

By changing the conditions in the IF statement, you can add files based on other conditions.
If fsoFile.DateLastModified > dtNew And Right(fsoFile.Name, 5) = ".docx" Then

The macro uses the Scripting Runtime to read the HTML file. You'll need to set a reference to it in the VB Editor's Tools, References dialog.
Set a reference to scripting runtime

 

Sub AttachNewestFile()
' You need to set a reference to the scripting object
Dim objMail As Outlook.MailItem
Dim fso As Scripting.FileSystemObject
 
 Dim strFile As String
 Dim fsoFile As Scripting.File
 Dim fsoFldr As Scripting.Folder
 Dim dtNew As Date, sNew As String
 
 Set fso = New Scripting.FileSystemObject
 
 strFile = "C:\Users\Administrator\Documents\"
   
 Set fsoFldr = fso.GetFolder(strFile)
     
     For Each fsoFile In fsoFldr.Files
' check the extension and age
         If fsoFile.DateLastModified > dtNew And Right(fsoFile.Name, 5) = ".docx" Then
             sNew = fsoFile.Path
             dtNew = fsoFile.DateLastModified
             Debug.Print sNew & dtNew
         End If
     Next fsoFile
 
 'Create e-mail item
 Set objMail = Application.CreateItem(olMailItem)

 With objMail
 .BodyFormat = olFormatHTML
 .HTMLBody = "Here is the file you asked for"
 .Attachments.Add sNew
 .Display
 End With
End Sub

Attach Two Files

This version of the macro gets the newest document then finds the Excel with the same 4 first letters and inserts it into a new message.

Sub AttachTwoFiles()
' You need to set a reference to the scripting object
Dim objMail As Outlook.MailItem
Dim fso As Scripting.FileSystemObject
Dim fsoFile As Scripting.File
Dim fsoFldr As Scripting.Folder

 Dim strFilePath As String, strDoc As String
 Dim strExcel As String, strName As String
 Dim dtNew As Date, sNew As String
 
 Set fso = New Scripting.FileSystemObject
 
 strFilePath = "C:\Users\Administrator\Documents\"
   
 Set fsoFldr = fso.GetFolder(strFilePath)
     
     For Each fsoFile In fsoFldr.Files
         If fsoFile.DateLastModified > dtNew And Right(fsoFile.Name, 5) = ".docx" Then
             sNew = fsoFile.Path
             dtNew = fsoFile.DateLastModified
             Debug.Print sNew & dtNew
         End If
     Next fsoFile
     
 strDoc = sNew

strName = Right(sNew, Len(sNew) - Len(strFilePath))
strName = Left(strName, 4)

    For Each fsoFile In fsoFldr.Files
        If Left(fsoFile.Name, 4) = strName And Right(fsoFile.Name, 5) = ".xlsx" Then
            sNew = fsoFile.Path
        End If
    Next fsoFile

strExcel = sNew

 'Create e-mail item
 Set objMail = Application.CreateItem(olMailItem)

 With objMail
 .BodyFormat = olFormatHTML
 .HTMLBody = "Here is the file you asked for"
 .Attachments.Add strDoc
 .Attachments.Add strExcel
 .Display
 End With
End Sub

Attach Newest File to Message in Reading Pane

This macro works with Outlook 2013/2016's Reading Pane Compose feature and attaches the newest message to the reply in the Reading Pane.

Sub AttachNewestFileReadingPane()
' You need to set a reference to the scripting object
Dim objMail As Outlook.MailItem
Dim fso As Scripting.FileSystemObject
 
 Dim strFile As String
 Dim fsoFile As Scripting.File
 Dim fsoFldr As Scripting.Folder
 Dim dtNew As Date, sNew As String
 
 Dim exp As Explorer
 
 Set exp = Application.ActiveExplorer
 Set objMail = exp.ActiveInlineResponse
 If Not objMail Is Nothing Then
 
 Set fso = New Scripting.FileSystemObject
 
 strFile = "C:\Users\Diane\Documents\"
   
 Set fsoFldr = fso.GetFolder(strFile)
    
    For Each fsoFile In fsoFldr.Files
' check the age
         If fsoFile.DateCreated > dtNew Then
             sNew = fsoFile.Path
             dtNew = fsoFile.DateCreated
             Debug.Print sNew, dtNew
        End If

 Next fsoFile
 
    With objMail
        .Attachments.Add sNew
    End With
 End If
 
End Sub

Send a File to a Contact

This version of the macro sends a file named for the selected contact.

Send file to contact

If you use a different filename format, for example "MarySmith" or "smith-mary", a simple macro edit will find the correct file:

strContact = objContact.FullName
Replace(strContact , " " , "")

Or use

strContact = lcase(objContact.lastName & "-" & objContact.firstName)

To use this macro, select the contact and run the macro.

Public Sub SendFileToContact()
Dim objApp As Outlook.Application
Dim objContact As ContactItem
 
Dim objMail As Outlook.MailItem
Dim fso As Scripting.FileSystemObject
Dim fsoFile As Scripting.File
Dim fsoFldr As Scripting.Folder

 Dim strFilePath As String, strDoc As String
 Dim strExcel As String, strName As String
 Dim strContact As String, sNew As String
 
Set objApp = Application
Set objContact = objApp.ActiveExplorer.Selection.Item(1)
strContact = objContact.FullName

Set fso = New Scripting.FileSystemObject
 
 strFilePath = "C:\Users\Administrator\Documents\"
   
 Set fsoFldr = fso.GetFolder(strFilePath)
     
     For Each fsoFile In fsoFldr.Files
         If Left(fsoFile.Name, Len(strContact)) = strContact And Right(fsoFile.Name, 5) = ".docx" Then
             sNew = fsoFile.Path
             Debug.Print sNew & dtNew
         End If
     Next fsoFile
     
 strDoc = sNew
 'Create e-mail item
 Set objMail = objApp.CreateItem(olMailItem)

 With objMail
 .To = objContact.Email1Address
 .BodyFormat = olFormatHTML
 .HTMLBody = "Here is the file you asked for"
 .Attachments.Add strDoc
 .Display
 End With
 
 Set objApp = Nothing
End Sub

More Information

Send a new message to From address of selected messages
Send email to all addresses for one Contact
Use an Outlook Macro to Send Files by Email

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

Use a Macro to Attach Files to New Messages was last modified: August 7th, 2016 by Diane Poremsky

Related Posts:

  • Use an Outlook Macro to Send Files by Email
  • Create a New Message using an HTML File or Stationery
  • Apply Outlook Stationery to Replies and Forwards
  • Use VBA to open Outlook messages stored in the file system

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

Serge
August 10, 2021 7:58 pm

Hi Diane,

thanks for your lights ! Is there a way, in reading pane, to open the "insert attachment dialog", opened in the dowloads folder by default, or any other folder I could put in the macro ?

Best regards

0
0
Reply
WARD DE GEEST
May 16, 2020 7:35 am

Hi Diane,
How do I add an existing file to an Outlook message that is already started.
All VBA codes here generates a new outlook email message.
I want to automate (add file, choose file, add), in 1 click. The file is the same for each message.
(Not all outgoing messages should contain this file).
As Outlook has no recorder, I need some help to fix this.
Tnahks, Eduard.

0
0
Reply
Jay
September 16, 2018 8:54 pm

Diane, hello. I'm trying to find some code that would automate sending multiple emails to selected email recipients, plus an attachment specific to each email. The emails contain reports that are required to be sent once a month. The subject line for each email changes according to the attachment (e.g, F4333/K54 TO001 Cost Report (Aug 2018), F4333/K54 TO005 Cost Report (Aug 2018), etc.) When the TO number changes, the recipients change. I'm currently using templates specific to each TO where I drag the specific attachment into each email template, verify it, then send. I'm currently sending around 120 emails a month. Then the next month there may be additions or subtractions to the TO list. Was thinking of having a macro button in Outlook specific to each "K" number, like K54, K877, K987, etc. and the corresponding TO templates under each "K" level macro. Once clicked on, an input box would ask for the directory to pull the attachment from (as the location changes each month) and I can use one of your filters to pull the correct attachment based on the first 12 characters or so. I've looked through many of your examples, the closest is "Open a Template… Read more »

0
0
Reply
Jimbo
August 15, 2018 8:09 pm

Hi Dianne
Is it possible to have a macro to just add a standard attachment which i will point to with a button on the ribbon in a new email?

Even better, asI have probably 5 or 6 of these standard ones...can i add a custom dropdown to the ribbon and add files to it?

0
0
Reply
Chris
September 15, 2016 4:47 pm

Hi Diane,
. Can this macro be modified to automatically open a .oft template and then attach the newest .pdf from a folder on a network drive?

0
0
Reply
Diane Poremsky
Author
Reply to  Chris
September 15, 2016 8:39 pm

Should just need to replace
Set objMail = Application.CreateItem(olMailItem)
with
Set objMail = Application.CreateItem("C:\path\template.oft")

getting the attachment works the same as in the macro - you just need to use the network path in the filepath.
strFilePath = "\\computer\network\path\"

0
0
Reply
Rebecca
Reply to  Diane Poremsky
March 9, 2021 9:20 pm

I can't seem to get it to recognise the PDF file type when retreiving the item, it only works for docx, pptx etc.

0
0
Reply
Diane Poremsky
Author
Reply to  Rebecca
March 9, 2021 9:49 pm

You need to change the count and the extension:
Right(fsoFile.Name, 5) = ".docx" Then
to
Right(fsoFile.Name, ) = ".pdf" Then

1
0
Reply
Rebecca
Reply to  Diane Poremsky
March 10, 2021 12:45 am

Changed it to a 4 and it seemed to work, thank you!

0
0
Reply
Tracy H
December 31, 2015 12:26 pm

Hi Diane,

I would like to attach 8 files to one email monthly, the file names are static with the only change being the date at the end of the file. All files begin with "NP_" and end in "yyyy-mm-dd.txt" All of the files are stored in the same directory. filename = NP_Dissolution2015-12-01. The "Dissolution" part is what changes. All of the files are also created on the same day of the month. (So the next group will be created on 01-04-2015.

Is there a way to script the email message to automatically grab the 8 files and attach them?

0
0
Reply
Diane Poremsky
Author
Reply to  Tracy H
December 31, 2015 11:08 pm

you'd change this -
For Each fsoFile In fsoFldr.Files
If Left(fsoFile.Name, 4) = strName And Right(fsoFile.Name, 5) = ".xlsx" Then
sNew = fsoFile.Path
End If
I think this might work -

For Each fsoFile In fsoFldr.Files
If Right(fsoFile.Name, 14) = format(date, "yyyy-mm-dd") & ".txt" Then
sNew = fsoFile.Path
End If

0
0
Reply
Mitch
October 16, 2015 3:39 pm

I should have included that in the first message. All the items are located in one folder in the C drive.

0
0
Reply
Mitch
October 2, 2015 4:21 pm

Hi Diane,

Weekly I send 3 unique PDFs to around 15 different email recipients (45 total PDFs, 15 emails). Each of the 3 PDFs (going to 1 recipient) begins with a custom name. i.e one recipient gets BOB1, BOB2, BOB3, and another gets SARA1, SARA2, SARA3. I would like to use a macro to search in the C drive for the PDF based on the beginning phrase, grab the files that match it, look up the email address associated with the beginning phrase, and then email them out.

0
0
Reply
Diane Poremsky
Author
Reply to  Mitch
October 15, 2015 7:55 am

It would be a lot easier if all of the files are in one folder - VBA would need to check every folder and it would be slow. If it knows to look in a specific folder, it would be much faster. Picking up the files is fairly easy as long as they use a uniform name that it can detect.

0
0
Reply

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

Latest EMO: Vol. 30 Issue 34

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
  • Mail Templates in Outlook for Windows (and Web)
  • How to Remove the Primary Account from Outlook
  • Adjusting Outlook's Zoom Setting in Email
  • This operation has been cancelled due to restrictions
  • Reset the New Outlook Profile
  • Disable "Always ask before opening" Dialog
  • How to Hide or Delete Outlook's Default Folders
  • Removing Suggested Accounts in New Outlook
  • Remove a password from an Outlook *.pst File
  • 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