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

Macro to Print Outlook email attachments as they arrive

Slipstick Systems

› Developer › Macro to Print Outlook email attachments as they arrive

Last reviewed on September 30, 2014     228 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.

Today's entry in the lazy programmer series involves tweaking the code sample at Attachment: Print received attachments immediately so that it works with 4-character extensions and also with 64-bit Outlook 2010 or 2013. (The original macro works with 32-bit Outlook).

For third party add-ins and utilities, see Print Email (and Attachments) on Arrival

The code looks at the last 4 characters, including the period and will work as long as you use 4 characters in each extension we want to check.

Case "xlsx", "docx", ".pdf", ".doc", ".xls"

To use the macro with 64-bit Outlook, you need to add PtrSafe to Declare:

Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias _

Print received attachments immediately code sample

Original code was written for 32-bit Outlook and 3 character file extensions.

To use, open the VBA editor using Alt+F11 and paste the following code into ThisOutlookSession. Edit the code as needed then click in the Application_Startup() macro and press Run button (F8). This starts the macro without the need to restart Outlook.

' Written by Michael Bauer, vboffice.net
' //www.vboffice.net/en/developers/print-attachments-automatically

' use  Declare PtrSafe Function with 64-bit Outlook
Private Declare Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
  Dim Ns As Outlook.NameSpace
  Dim Folder As Outlook.MAPIFolder

  Set Ns = Application.GetNamespace("MAPI")
  Set Folder = Ns.GetDefaultFolder(olFolderInbox)
  Set Items = Folder.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
  If TypeOf Item Is Outlook.MailItem Then
    PrintAttachments Item
  End If
End Sub

Private Sub PrintAttachments(oMail As Outlook.MailItem)
  On Error Resume Next
  Dim colAtts As Outlook.Attachments
  Dim oAtt As Outlook.Attachment
  Dim sFile As String
  Dim sDirectory As String
  Dim sFileType As String

  sDirectory = "D:\Attachments\"

  Set colAtts = oMail.Attachments

  If colAtts.Count Then
    For Each oAtt In colAtts

' This code looks at the last 4 characters in a filename
      sFileType = LCase$(right$(oAtt.FileName, 4))

      Select Case sFileType

' Add additional file types below
      Case ".xls", ".doc", "docx"

        sFile = sDirectory  & oAtt.FileName
        oAtt.SaveAsFile sFile
        ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0
      End Select
    Next
  End If
End Sub

Print attachments then move the message

If you want to print the attachment then move the message to another folder, you'll either need to add the move code to the ItemAdd macro or add another macro and call it from the ItemAdd macro.

In this example, I'm adding a new macro and calling it from the ItemAdd macro, after the PrintAttachments macro is called.

  If TypeOf Item Is Outlook.MailItem Then
    PrintAttachments Item
    MovePrintedMail Item
  End If

At the end of the module, after the PrintAttachments macro, add the move macro. This macro assumes the "move to folder" is a subfolder of the Inbox. Don't forget to change the mailbox name, using the name as it appears in the Folder list (it's your email address in newer versions of Outlook).

Sub MovePrintedMail(oMail As Outlook.MailItem)
  Dim objDestFolder As Outlook.MAPIFolder

   Set objDestFolder = Session.Folders("mailbox name")._
     Folders("Inbox").Folders("Printed")

     oMail.Move objDestFolder 
   
  Set objDestFolder = Nothing
End Sub

 

Print Attachments on Selected Messages

To convert the macro to print attachments on a selected messages as needed, you need to remove the startup and itemadd macros and either use code that picks up the selected item or loops through the selected items.

This version will work either one or more selected items.

' Based on macro written by Michael Bauer, vboffice.net
' //www.vboffice.net/en/developers/print-attachments-automatically
 
' use  Declare PtrSafe Function with 64-bit Outlook
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Sub PrintAttachmentsSelectedMsg()
 Dim oMail As Outlook.MailItem
 Dim obj As Object
 'On Error Resume Next
 
For Each obj In ActiveExplorer.Selection
Set oMail = obj
 
  Dim colAtts As Outlook.Attachments
  Dim oAtt As Outlook.Attachment
  Dim sFile As String
  Dim sDirectory As String
  Dim sFileType As String
 
  sDirectory = "C:\Users\Diane\Docs\"
 
  Set colAtts = oMail.Attachments
 
  If colAtts.Count Then
    For Each oAtt In colAtts
 
' This code looks at the last 4 characters in a filename
      sFileType = LCase$(Right$(oAtt.filename, 4))
 
      Select Case sFileType
 
' Add additional file types below
      Case ".xls", ".doc", "docx"
 
        sFile = sDirectory & oAtt.filename
        oAtt.SaveAsFile sFile
        ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0
      End Select
    Next
  End If
  
Next
End Sub

 

Use Acrobat's Printer Options

If you own Adobe Acrobat, you can set the pages you want to print and "shrink to fit" using the PrintPages function of Acrobat:
Function PrintPages(nFirstPage As Long, nLastPage As Long, nPSLevel As Long, bBinaryOk As Long, bShrinkToFit As Long) As Boolean

To use Acrobat's object model, you need to set a reference to Acrobat in the VB Editor's Tool, References dialog box.

This will not work with Reader, you need to own Acrobat. I tested it with Acrobat X but it should work with any version of Acrobat. To the best of my knowledge, both Acrobat Standard and Acrobat Pro include OLE support.

Change the Select Case code in the PrintAttachments macro to the following. If you are only printing PDF files, you can remove the Case statement that prints Excel and Word files.

To print no more than first 2 pages, use AcrobatPrint sFile


      Select Case sFileType

' Add additional file types below
      Case ".xls", ".doc", "docx"
 
        sFile = sDirectory & oAtt.FileName
        oAtt.SaveAsFile sFile
        ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0
        
' Print PDF
     Case ".pdf"
        sFile = sDirectory & oAtt.FileName
        oAtt.SaveAsFile sFile
        AcrobatPrint sFile, "All"

      End Select

After changing the Select case block, add the AcrobatPrint macro to your module, inserting it after the PrintAttachments macro.


Public Sub AcrobatPrint(FileName As String, PrintMode As String)

     Dim AcroExchApp As Acrobat.CAcroApp
     Dim AcroExchAVDoc As Acrobat.CAcroAVDoc
     Dim AcroExchPDDoc As Acrobat.CAcroPDDoc
     Dim num As Integer

     Set AcroExchApp = CreateObject("AcroExch.App")
     Set AcroExchAVDoc = CreateObject("AcroExch.AVDoc")

     ' Open the pdf file
     AcroExchAVDoc.Open FileName, ""

     Set AcroExchPDDoc = AcroExchAVDoc.GetPDDoc

     ' Get the number of pages for this pdf
     ' Subtract one because the count is 0 based
     num = AcroExchPDDoc.GetNumPages - 1

     If PrintMode = "All" Then

     ' Print Entire Document 
     ' Last value is shrinktofit
           Call AcroExchAVDoc.PrintPages(0, num, 2, 1, 1)
     Else
           If num = 0 Then
               ' If one page, print document
                Call AcroExchAVDoc.PrintPages(0, num, 2, 1, 1)
           Else
               'Print first two pages
                Call AcroExchAVDoc.PrintPages(0, 1, 2, 1, 1)
           End If
     End If
  
     AcroExchApp.Exit
     AcroExchAVDoc.Close (True)
     AcroExchPDDoc.Close

End Sub

Run a script version

This code sample is used in a run a script rule and deletes the message after printing the attached pdf.

to use, add the macro to a module, create a rule with the conditions you want to use and select run a script as the only action then select this script. For more information, see Run a Script rules.

Private Declare Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
 
  
 Sub PrintAttachments(oMail As Outlook.MailItem)
  Dim colAtts As Outlook.Attachments
  Dim oAtt As Outlook.Attachment
  Dim sFile As String
  Dim sDirectory As String
  Dim sFileType As String
 
  sDirectory = "C:\Users\Diane\Documents\Attach\"
 
  Set colAtts = oMail.Attachments
 
  If colAtts.Count Then
    For Each oAtt In colAtts
 
' This code looks at the last 4 characters in a filename
      sFileType = LCase$(Right$(oAtt.FileName, 4))
 
      Select Case sFileType
 
' Add additional file types below
      Case ".pdf", ".doc", "docx"
 
        sFile = sDirectory & oAtt.FileName
        oAtt.SaveAsFile sFile
        ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0
      End Select
    Next
    
  End If
     oMail.Delete
 

End Sub

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 use the macro code in ThisOutlookSession:

  1. Expand Project1 and double click on ThisOutlookSession.
  2. Copy then paste the macro into ThisOutlookSession. (Click within the code, Select All using Ctrl+A, Ctrl+C to copy, Ctrl+V to paste.)
  3. Make sure folder in the sDirectory path exists; if not, change it to a folder that exists.
  4. Click in the Application_Startup macro and press Run (or F8) to kick start it without restarting Outlook.
  5. Send yourself a message with a Word document attachment. Outlook should print it on arrival.

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

Macro to Print Outlook email attachments as they arrive was last modified: September 30th, 2014 by Diane Poremsky

Related Posts:

  • Search PDF Attachments and Forward
  • Save Messages and Attachments to a New Folder
  • Save and Open an Attachment using VBA
  • Use VBA to move messages with attachments

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

ramesh
April 22, 2021 3:49 am

Dear ,

thanks for the script is working fine , but i need to print specific print instead of default printer ,currently "ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0" is printing directly to default  printer .
and it  prints  irregularly if pdf  , to solve this issue , i add "sleep 3000" after the shellexecute.

 how to select a specific printer.,

how can solve it .

0
0
Reply
Diane Poremsky
Author
Reply to  ramesh
April 22, 2021 8:32 am

No, you can't change the printer in Outlook.

You can try changing the default before printing - then change it back.
Dim Wsh As Object
  Set Wsh = CreateObject("WScript.Network")
  Wsh.setDefaultPrinter "the printer name"

repeat the lines above with the usual default printer name to change it back.

0
0
Reply
ramesh
Reply to  Diane Poremsky
April 24, 2021 1:03 am

Thanks diane, for the reply , it is working , but is it possible to right a program to execute this , means that find the default printer on before and save as string , change later it as default.
it is much appreciated .

Best regards

0
0
Reply
Sridar
October 20, 2020 10:02 am

HI
Kindly provide code to print the attachment in ascending order based on the first 11 Digit of the attachment name .

0
0
Reply
Diane Poremsky
Author
Reply to  Sridar
April 22, 2021 8:23 am

the attachments will be printed in the order the attachment's app processes and renders them - to control the order you would need to use a 3rd party utility.

0
0
Reply
David Sivewright
December 18, 2019 11:41 pm

Im getting a syntax error. with this.

Sub MovePrintedMail(oMail As Outlook.MailItem)
Dim objDestFolder As Outlook.MAPIFolder

Set objDestFolder = Session.Folders("ap@hipco.com").
Folders("Inbox").Folders ("Printed")

oMail.Move objDestFolder

Set objDestFolder = Nothing
End Sub

0
0
Reply
Diane Poremsky
Author
Reply to  David Sivewright
December 18, 2019 11:45 pm

Which line is erroring?

0
0
Reply
Carl
December 18, 2019 5:12 pm

How would the VBA code be modified to include situations when the email message has another email message as an attachment and that second email message has the pdf, etc. file attachment that you want to automatically print?

0
0
Reply
Diane Poremsky
Author
Reply to  Carl
December 18, 2019 11:19 pm

You would need to open (using .display) the second email than use application.ActiveInspector.CurrentItem to reference it - then you can open the attachment

0
0
Reply
Carl
Reply to  Diane Poremsky
December 19, 2019 10:25 am

Thank you!

0
0
Reply
Patrícia Costa
November 6, 2019 5:36 am

Hello!

I would like to print the PDF file from certain emails (with the same subject), also, in this file I just want to Print the second page. How should I proceed to create this rule and Macro?

Thank you,
Patrícia

0
0
Reply
Diane Poremsky
Author
Reply to  Patrícia Costa
November 6, 2019 3:52 pm

The first 2 numbers in this line are first page to print, last to print - but the page numbers are zero-based - so 0 = page 1, 1 = page 2. Therefor, you use 1,1 as the first 2 numbers to print only page 2:
Call AcroExchAVDoc.PrintPages(1,1, 2, 1, 1)

https://www.poremsky.com/office/print-pdf-vba/

0
0
Reply
Alex Gamboa
June 14, 2019 11:36 am

I am currently using a trial version of the EZDetach add-in for outlook to automatically save attachments from incoming emails onto a folder on my desktop and then automatically print those attachments. I am trying to find a way to filter through those attachments to be able to auto print three different types of invoices to three different colors of paper. I either want it to auto print to different trays or purchase more printers and have each invoice print to a different printer. Please let me know if this is possible

0
0
Reply
Joe
September 13, 2018 3:08 pm

Will this code work with Nitro Pro?

0
0
Reply
Diane Poremsky
Author
Reply to  Joe
September 13, 2018 4:00 pm

It might, since it just calls up the default application and uses shell commands. I dont have nitro to test it though.

0
0
Reply
Steven
June 26, 2018 8:37 am

I am using the script to print then delete the attachment, but it seems that it is double printing some of them and not printing others. The odd thing about this is that they all show up in the deleted folder as they should and in the order they should with no duplicates. Very strange. Any ideas?

0
0
Reply

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

Latest EMO: Vol. 30 Issue 33

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
  • Adjusting Outlook's Zoom Setting in Email
  • How to Remove the Primary Account from Outlook
  • Disable "Always ask before opening" Dialog
  • Reset the New Outlook Profile
  • Use PowerShell to get a list of Distribution Group members
  • Shared Mailboxes and the Default 'Send From' Account
  • Office Outlook Add-ins
  • Automatically BCC All Messages
  • Gmail All Mail and Outlook’s Archive folder
  • 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
  • New Outlook: Show To, CC, BCC in Replies
  • Insert Word Document into Email using VBA
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

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

New Outlook: Show To, CC, BCC in Replies

Insert Word Document into Email using VBA

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