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

Save Outlook Email as a PDF

Slipstick Systems

› Developer › Code Samples › Save Outlook Email as a PDF

Last reviewed on August 29, 2018     163 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.

There are two ways to save Outlook messages in PDF format: by printing to a PDF printer or saving in PDF format from Word. This sample shows how to use the Word Object Model to save as PDF. (There is a third way: use Adobe Acrobat's package feature. It makes a really nice PDF archive, if you own Acrobat.)

This code sample will save one or more selected Outlook email messages as a PDF file. Because it uses Word object to save, this code could easily be tweaked to save messages in any format Word can save as.

Don't forget to set a reference to the Word object library in Tools > References. Select the correct version for your version of Office. (Most people will only have one entry, the correct one.)
Set the VB references

A version of this macro to use in a run a script rule is here.

Sub SaveMessageAsPDF()
     
    Dim Selection As Selection
    Dim obj As Object
    Dim Item As MailItem
     
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Set wrdApp = CreateObject("Word.Application")
    Set Selection = Application.ActiveExplorer.Selection

For Each obj In Selection
 
    Set Item = obj
    
    Dim FSO As Object, TmpFolder As Object
    Dim sName As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set tmpFileName = FSO.GetSpecialFolder(2)
    
    sName = Item.Subject
    ReplaceCharsForFileName sName, "-"
    tmpFileName = tmpFileName & "\" & sName & ".mht"
    
    Item.SaveAs tmpFileName, olMHTML
    
    
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)
  
    Dim WshShell As Object
    Dim SpecialPath As String
    Dim strToSaveAs As String
    Set WshShell = CreateObject("WScript.Shell")
    MyDocs = WshShell.SpecialFolders(16)
       
strToSaveAs = MyDocs & "\" & sName & ".pdf"
 
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
   sName = sName & Format(Now, "hhmmss")
   strToSaveAs = MyDocs & "\" & sName & ".pdf"
End If
  
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    strToSaveAs, ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
    Range:=wdExportAllDocument, From:=0, To:=0, Item:= _
    wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
    BitmapMissingFonts:=True, UseISO19005_1:=False
             
Next obj
    wrdDoc.Close
    wrdApp.Quit
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
    Set WshShell = Nothing
    Set obj = Nothing
    Set Selection = Nothing
    Set Item = Nothing
 
End Sub
 
' This function removes invalid and other characters from file names
Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
  sName = Replace(sName, "/", sChr)
  sName = Replace(sName, "\", sChr)
  sName = Replace(sName, ":", sChr)
  sName = Replace(sName, "?", sChr)
  sName = Replace(sName, Chr(34), sChr)
  sName = Replace(sName, "<", sChr)
  sName = Replace(sName, ">", sChr)
  sName = Replace(sName, "|", sChr)
  sName = Replace(sName, "&", sChr)
  sName = Replace(sName, "%", sChr)
  sName = Replace(sName, "*", sChr)
  sName = Replace(sName, " ", sChr)
  sName = Replace(sName, "{", sChr)
  sName = Replace(sName, "[", sChr)
  sName = Replace(sName, "]", sChr)
  sName = Replace(sName, "}", sChr)
  sName = Replace(sName, "!", sChr)
End Sub

Save without the Headers

This version of the macro saves the message without the short To/From/subject headers normally found at the top of a printed message.

message header

Sub SaveMessageAsPDF()
     
'Set up the browser
    Dim browser As String
    Dim ConvertMail As Boolean
    Dim CheckHTML As Boolean
    browser = "C:\Program Files\Internet Explorer\iexplore.exe"
    ConvertMail = False
    CheckHTML = True
     
    Dim Selection As Selection
    Dim obj As Object
    Dim Item As MailItem
     
 
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Set wrdApp = CreateObject("Word.Application")
    Set Selection = Application.ActiveExplorer.Selection

For Each obj In Selection
 
    Set Item = obj
    
    Dim FSO As Object, TmpFolder As Object
    Dim sName As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set tmpFileName = FSO.GetSpecialFolder(2)
    
    sName = Item.Subject
    ReplaceCharsForFileName sName, "-"
    tmpFileName = tmpFileName & "\" & sName & ".htm"
    

 Dim ConvertHTML As Boolean
    ConvertHTML = True

    If Item.BodyFormat = olFormatHTML And ConvertMail = False Then
        Dim rawHTML As String
        rawHTML = Item.HTMLBody

        If CheckHTML = False Then
            ConvertHTML = False
        Else
            If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
                ConvertHTML = False
            End If
        End If
    End If
     If ConvertHTML = False Then
            Set objFile = FSO.CreateTextFile(tmpFileName, True)
            objFile.Write "" & rawHTML
            objFile.Close
            Set objFile = Nothing
    Else
            Item.SaveAs tmpFileName, olHTML
    End If
   
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)
  
    Dim WshShell As Object
    Dim SpecialPath As String
    Dim strToSaveAs As String
    Set WshShell = CreateObject("WScript.Shell")
    MyDocs = WshShell.SpecialFolders(16)
       
strToSaveAs = MyDocs & "\" & sName & ".pdf"
 
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
   sName = sName & Format(Now, "hhmmss")
   strToSaveAs = MyDocs & "\" & sName & ".pdf"
End If
  
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    strToSaveAs, ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
    Range:=wdExportAllDocument, From:=0, To:=0, Item:= _
    wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
    BitmapMissingFonts:=True, UseISO19005_1:=False
             
Next obj
    wrdDoc.Close
    wrdApp.Quit
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
    Set WshShell = Nothing
    Set obj = Nothing
    Set Selection = Nothing
    Set Item = Nothing
 
End Sub
 
' This function removes invalid and other characters from file names
Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
  sName = Replace(sName, "/", sChr)
  sName = Replace(sName, "\", sChr)
  sName = Replace(sName, ":", sChr)
  sName = Replace(sName, "?", sChr)
  sName = Replace(sName, Chr(34), sChr)
  sName = Replace(sName, "<", sChr)
  sName = Replace(sName, ">", sChr)
  sName = Replace(sName, "|", sChr)
  sName = Replace(sName, "&", sChr)
  sName = Replace(sName, "%", sChr)
  sName = Replace(sName, "*", sChr)
  sName = Replace(sName, " ", sChr)
  sName = Replace(sName, "{", sChr)
  sName = Replace(sName, "[", sChr)
  sName = Replace(sName, "]", sChr)
  sName = Replace(sName, "}", sChr)
  sName = Replace(sName, "!", sChr)
End Sub

Save as a DOCX File

To save the message as a Word Document using the DOCX file type, replace the code blocks that saves as a pdf with the code below.

wrdApp.ActiveDocument.SaveAs2 FileName:= _
        strToSaveAs, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=15

 

How to Use Macros

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

To check your macro security in Outlook 2010 and above, 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

  • How to Save Email in Windows File System
  • Import Messages from File System into Outlook Folders
  • OWA: Save Messages to My Documents
  • Save a Message as HTML and Delete the (Annoying) Folder
  • Save email message as text file
  • Save Outlook Email as a PDF
  • Save Selected Email Message as .msg File
  • Saving All Messages to the Hard Drive Using VBA

Print Email (and Attachments) on Arrival has a list of utilities that can print messages and attachments.

Save Outlook Email as a PDF was last modified: August 29th, 2018 by Diane Poremsky
Post Views: 112

Related Posts:

  • Save Messages as *.DOC or *.DOCX File Type
  • Save all incoming messages to the hard drive
  • Save email message as text file
  • Save Selected Email Message as .msg File

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.

Comments

  1. Pedro says

    March 13, 2023 at 10:50 am

    Hi Diane,

    is it possible to prompt for the file location on a save as dialog?
    Thanks

    Reply
    • Diane Poremsky says

      March 13, 2023 at 10:22 pm

      You can use the browse for folder option in this article - https://www.slipstick.com/developer/code-samples/windows-filepaths-macro/

      Reply
      • Pedro says

        March 14, 2023 at 5:51 am

        Hi Diane,
        i don't know what to change in the code to include BrowseForFolderCan you help?
        Thanks

      • Pedro says

        March 15, 2023 at 10:06 am

        Hi Diane,
        i don't know what part of the code to modify.
        Can you help please?

  2. Kennan Bieniawski says

    October 6, 2022 at 10:33 am

    I have code similar to this shown below. However I am having trouble as when saving emails that have photos they are often cut-off. I can't seem to find a way to get the photos to either shrink to fit the dimensions or some other method.

    Reply
    • James Martin says

      April 27, 2023 at 6:43 am

      Hi Kennan,

      See the txt file of my bas file for my Macro Es. I use upper or lowercase initials for my Macros. Macro E is to save the email Header and body to Word.

      Towards the end of the macro you will see Macro s , to force high res embedded images to within the page margin.

      I have not cleaned out noted out code, as I have not resolved if Macro Es is run with Word App not open - I have to end task for the Word entry lower down in Task Manager, if run with Word App closed.

      The way I have saved the email details for the file name should be of interest. A lot of trial and error.

      There is some recent code added to flash up a MsgBox, for Macro L, in Excel which logs all my active windows, and productivity data, this is posted on my LinkedIn page.

      Reply
    • James Martin says

      April 27, 2023 at 7:24 am

      In addition to my previous comment, I also have amended versions of the Slipstick save attachments to a folder "save-attachments-to-the-hard-drive". Macro A.

      And the Slipstick macro for saving a txt version of an email, if needed. I call this Macro e "save-email-message-text-file".

      These 3 macros including Macro Es were critical to I'mproving productivity.

      There is a 4th Macro in Word to import image files downloaded from the Macro A to a temp folder you specify, and Import them at the cursor point. This saves a lot of time for an archiving role I have been doing.

      For pdfs I have not created a macro to control the pages if under 11 pages (we have a 4MB file upload limit), and import these at the cursor point. I am manually rotating pdfs to landscape, full screening, and pasting into the docx.

      I have Macro R to rotate all or selected images. (via Grey Maxey).

      I also have Macro C/c to compress images by 150/96ppi.

      Macro B for page/section Break, and Header and Footer unlink - is from Greg Maxey.

      Macro S is to maximise images, as they shrink when moved in the document.

      Macro T is to force tables mainly in email signatures to the page width, but does not always work on the cybertext.wordpress.com website "word-macro-to-autofit-all-tables-to-the-window-size/".

      Macro P is to Print, open doc/docx/rtf/odt to pdf in the Temp attachments folder, so I can insert easily into the Macro Es docx save.

      Macro X closes the active file in Word, although a minor action this saves a lot of time each day, as I use it so often.

      All my macros are single click on the Quick Access Toolbar.

      Reply
  3. James Martin says

    September 24, 2021 at 8:07 am

    I have got the pdf Outlook Item Macro to work, with change to docx with Header, as this file type is better for editing the order of embedded customer photos of documents. I need some code when the objects/items from outlook are moved to Word, before the saving.
    Basically customers upload images of document pages from mobiles, and the images are embedded in the email body and not classed as attachments. Most photos are oversized in the docx produced.

    I currently forward selected email and copy the Forwarded email body and paste H into docx and this naturally wraps all images within the margins even if in landscape.

    [I have a rotation macro to correct selected or all images by 90, 180 or 270 degrees, I received help from http://www.gregmaxey.com to get the two listboxes to work in a UserForm for the select or all rotation macros.]

    I have noticed cutting the images in the docx from the run macro and repasting with paste K, resolves the wrapping problem, but I am struggling to code this. The other problem with my manual method is that the attachments list is not included in the forwarded email body and the most recent email header, so if I code this it would not be ideal (too complicated for me to code).

    Any help for a probable simple coding solution, would be greatly received. I need this Macro, along with the save email as text, and save all attachments which I have got to work from this site
    [for the attachments macro I added:
    Kill "C:\folder\folder2\*.*"
    To clear the folder up a level from where the docx and txt macros are saved, before each run of the attachments macro, the kill code is the first line of the sub.

    Reply
  4. Philip Coltharp says

    June 14, 2021 at 2:14 pm

    Thank you Diane, thank you, thank you, thank you, thank you, thank you ...

    Reply
  5. Matt Lane says

    July 5, 2020 at 1:56 pm

    Hey Diane, Thank you for posting. Love how the code includes the headers. Having a bit of trouble. When i select items from my inbox, it saves them to the specified desktop folder. When i try to select emails from a sub folder of my outlook inbox, I run into an error "Outlook cannot save this file because it is already open elsewhere." on the following line of code: Item.SaveAs tmpFileName, olMHTML. I like saving the emails to a subfolder as i need to save them for an access review. I have an outlook rule moving ~1000 of them to the subfolder so i can group them. Any ideas? Thanks!

    Reply
  6. Tapas says

    June 25, 2020 at 4:51 am

    Hi Diane,
    I have an email that has a table (or a picture) in it that gets cropped when i use this macro to save as pdf. Any suggestions to fit all data to a page in the pdf?
     

    Reply
  7. Javier says

    May 25, 2020 at 11:08 pm

    Hello Diane. When I have selected a confirmation (example: Accepted: invitation ...) this won't work and throw an error in here:

    For Each obj In Selection
    Set Item = obj

    The error message is:

    Run-time error '13': Type missmatch

    I guess confirmations are a different object.

    Do you know how I can fix it? I want to gather information from aa bunch of meeting confirmations.

    Thanks in advance.

    Reply
  8. Neelesh says

    December 1, 2019 at 12:28 am

    I get a debug error at Set objFile = FSO.CreateTextFile(tmpFileName, True)
    Sub SaveMessageAsPDF()

    'Set up the browser
    Dim browser As String
    Dim ConvertMail As Boolean
    Dim CheckHTML As Boolean
    browser = "C:\Program Files\Internet Explorer\iexplore.exe"
    ConvertMail = False
    CheckHTML = True

    Dim Selection As Selection
    Dim obj As Object
    Dim Item As MailItem

    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Set wrdApp = CreateObject("Word.Application")
    Set Selection = Application.ActiveExplorer.Selection

    For Each obj In Selection

    Set Item = obj

    Dim FSO As Object, TmpFolder As Object
    Dim sName As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set tmpFileName = FSO.GetSpecialFolder(2)

    sName = Item.Subject
    ReplaceCharsForFileName sName, "-"
    tmpFileName = tmpFileName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".htm"

    Dim ConvertHTML As Boolean
    ConvertHTML = True

    If Item.BodyFormat = olFormatHTML And ConvertMail = False Then
    Dim rawHTML As String
    rawHTML = Item.HTMLBody

    If CheckHTML = False Then
    ConvertHTML = False
    Else
    If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
    ConvertHTML = False
    End If
    End If
    End If
    If ConvertHTML = False Then
    Set objFile = FSO.CreateTextFile(tmpFileName, True)
    objFile.Write "" & rawHTML
    objFile.Close
    Set objFile = Nothing
    Else
    Item.SaveAs tmpFileName, olHTML
    End If

    Set wrdDoc = wrdApp.Documents.Open(FILENAME:=tmpFileName, Visible:=True)

    Dim WshShell As Object
    Dim SpecialPath As String
    Dim strToSaveAs As String
    Set WshShell = CreateObject("WScript.Shell")
    MyDocs = WshShell.SpecialFolders(16)

    strToSaveAs = MyDocs & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".pdf"

    ' check for duplicate filenames
    ' if matched, add the current time to the file name
    If FSO.FileExists(strToSaveAs) Then
    sName = sName & Format(Now, "hhmmss")
    strToSaveAs = MyDocs & "\" & sName & ".pdf"
    End If

    wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _

    Reply
    • Diane Poremsky says

      December 2, 2019 at 12:44 pm

      Does it give you an error message or just stop at that line? What do you have set for the filepath?
      tmpFileName = tmpFileName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".htm"

      Reply
  9. PaulD says

    November 22, 2019 at 2:46 am

    I just tried this with Outlook 2007 and Word 2003. Stepping through the code it generates the temp file, but fails to generate the pdf file. VBA isn't generating any errors and the macro happily runs to the end. Any idea what is going on?

    Reply
    • Diane Poremsky says

      November 22, 2019 at 7:56 am

      Does it skip any lines? Is the Word version a typo? Word 2003 may not support saving as PDF.

      Comment out all error handlers so it stops on errors. You may need set the editor to break on all errors - it usually only breaks on unhandled errors.

      Reply
      • PaulD says

        November 23, 2019 at 5:58 am

        Thanks for the tip. Yes Word 2003 cannot save to pdf. Never thought to check that. So I printed to a pdf printer addin which achieves the same result. Cheers

      • IzaB says

        December 7, 2020 at 1:14 am

        Windows 10 was blocking it, so I used a workaround you have for it and it is working now :)

      • IzaB says

        December 6, 2020 at 1:06 pm

        Hello Diane,
        I have the same problem. it generates the temp file, but fails to generate the pdf file. VBA isn't generating any errors and the macro happily runs to the end. I've word 2016 & outlook 2016. Any suggestions what I should do?

  10. Esteban Ramos says

    October 12, 2018 at 11:16 am

    Hello again Diane,

    Is there a way to have the message saved as DOCX directly to a specified folder without any prompts?

    Thanks,
    Esteban R.

    Reply
    • Diane Poremsky says

      October 13, 2018 at 1:05 am

      You can use a macro - an automatic startup macro will save all as they arrive or you can use a manual one - select the message, push a button. Either can be preconfigured to use either a hardcoded path.

      Reply
      • Esteban Ramos says

        October 16, 2018 at 1:14 pm

        Thank you, using the code what changes can I make to save it so a path?

        I see:

        strToSaveAs = MyDocs & "\" & sName & ".docx"

        ' check for duplicate filenames
        ' if matched, add the current time to the file name
        If FSO.FileExists(strToSaveAs) Then
        sName = sName & Format(Now, "hhmmss")
        strToSaveAs = MyDocs & "\" & sName & ".docx"
        End If

        Not sure what to edit to change to a specified path

      • Diane Poremsky says

        October 16, 2018 at 9:24 pm

        If you want to save to a specific path, you can change this line:
        strToSaveAs = MyDocs & "\" & sName & ".docx"
        to
        strToSaveAs = "c:\The new path\folder\subfolder\" & sName & ".docx"

      • Esteban Ramos says

        October 17, 2018 at 9:00 am

        Diane thanks for the replies, I changed the code as seen below. However it still save to Documents and not the specified folder. Im guessing it has to do with the 'Mydocs = wshell.special folders' line.

        --------------------------------------------------------------------------------------------
        Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)

        Dim WshShell As Object
        Dim SpecialPath As String
        Dim strToSaveAs As String
        Set WshShell = CreateObject("WScript.Shell")
        MyDocs = WshShell.SpecialFolders(16)

        strToSaveAs = "C:\Users\gonzae50\Documents\NEWVITALIZEEMAILS" & sName & ".docx"

        ' check for duplicate filenames
        ' if matched, add the current time to the file name
        If FSO.FileExists(strToSaveAs) Then
        sName = sName & Format(Now, "hhmmss")
        strToSaveAs = "C:\Users\gonzae50\Documents\NEWVITALIZEEMAILS" & sName & ".docx"
        End If

        wrdApp.ActiveDocument.SaveAs2 FileName:= _
        strToSaveAs, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=15

        ---------------------------------------------------------------------------------------------
        Do you know what I can do to get it to the folder?

        Thank you SO MUCH for all the amazing help!

      • Esteban Ramos says

        October 17, 2018 at 9:30 am

        Just an FYI the path has all the "/" not sure why they didn't come across on the pasting of the code.

      • Diane Poremsky says

        October 19, 2018 at 12:11 am

        It's wordpress - or, more accurately php - it removes the slashes. :(

      • Diane Poremsky says

        October 19, 2018 at 12:14 am

        You aren't using mydocs. or shouldn't be. Comment out or delete that line and see if it errors. Do you have a slash after the folder name ? This: Documents\NEWVITALIZEEMAILS" & sName & ".docx" = Documents\NEWVITALIZEEMAILSsname.docx
        Use a trailing slash in the strtosaveas path: Documents\NEWVITALIZEEMAILS\"

  11. Heather G Licklider says

    September 24, 2018 at 10:39 am

    how can I change the file saving naming convention to the Sent on date in the format "yyyy-mm-dd-hh-nn-ss-subject"

    Reply
    • Diane Poremsky says

      September 25, 2018 at 12:49 am

      Use Format(obj.SentOn, "yyyy-mm-dd-hh-nn-ss-") & obj.subject

      Reply
  12. Sam says

    June 26, 2018 at 11:09 am

    I often get an error with the .mht file still being open and not closing. This often happens if you run the script multiple times on the same email, but will also do it randomly.

    More importantly, when I restart my computer, several word documents open. It's as if the email is converting but the file stays open in the background, maybe in a temp file?

    Is there a way to "Kill" this? I have tried the kill command but it doesn't work.I think it has to do with this tmpFileName

    One last thing, If you run the script on the same email multiple times, it doesn't create another version. It says errors. I thought adding the date format after the name, as it looks like you did, but I couldn't get yours to work, nor mine.
    sName = sName & Format(dtDate, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem)

    Reply
    • Diane Poremsky says

      September 25, 2018 at 1:04 am

      >>
      More importantly, when I restart my computer, several word documents open. It's as if the email is converting but the file stays open in the background, maybe in a temp file?
      >>
      Windows 10? There is an option to reopen apps that were open when you closed Windows. I'm guessing that is the reason they reopen. Change this in Settings > Accounts > Sign-in Options to finish setting up apps after logging in.
      https://www.slipstick.com/outlook/outlook-loads-computer-boots/

      >>
      One last thing, If you run the script on the same email multiple times, it doesn't create another version. It says errors. I thought adding the date format after the name,
      >>
      That should be because the file already exists.
      Does it work if you use Now for the date?
      sName = sName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem)

      Reply
  13. Amanda says

    June 4, 2018 at 1:11 pm

    I have been using this script and the rule version of it for months. But all of a sudden I came into work this morning, and it's freezing outlook until i pull up task manager and find the WINWORD.EXE *32 process and end it. It is creating these and not closing them? The date is June 4th 2018. I'm not sure why i'm getting this error now, when in the past it's been fine.

    Reply
  14. Jim Bo says

    December 19, 2017 at 5:05 pm

    Hi Dianne - me again!
    All working well, except when the script tries to run, i get the following error. If i restart my computer it works again?:

    Run-time error '-2147467259 (80004005)': The export failed due to an unexpected error.

    What should i do? I have attached shots of the error and the screen reached with the debugger

    Reply
    • Diane Poremsky says

      December 19, 2017 at 8:15 pm

      What version of Office, Windows do you use? I can't find much information about possible causes for that error - but what i found involved Office 2007. I'm still looking for solutions.

      Reply
      • Jim Bo says

        December 19, 2017 at 8:18 pm

        I am using Windows 10 Pro / Office 2013

      • Diane Poremsky says

        December 19, 2017 at 8:19 pm

        Also, what pdf application do you use? This is the only comment I've found so far that the affected user said worked: "I uninstalled Foxit Reader and installed Adobe Reader 9 and rebooted..."

        I don't think the error message points to the filename, but triple check t o verify it is valid.

      • Jim Bo says

        December 19, 2017 at 8:31 pm

        I use Adobe Acrobat Reader DC. what do i need to check with the filename?

        The odd thing is it works fine after a reboot but then finally stops so i need to reboot?

      • Diane Poremsky says

        December 19, 2017 at 10:20 pm

        I'm not sure what you need to do - there is so little information out there, at least that I've found.

      • Jim Bo says

        January 28, 2018 at 4:20 pm

        Hi Diane. Just found i have an error with Word - some fonts it does not like - says there is not sufficient memory space to display the requested font. How do I change the font in the script to run as a rule?

      • Diane Poremsky says

        January 28, 2018 at 11:12 pm

        This script doesn't use fonts - the message and files would use the default fonts for word or the one used in the email.

        Is it a Type 1 font? They aren't supported in office 2013/2016. https://www.poremsky.com/office/type-1-and-other-older-fonts-not-supported-in-office-2013/

  15. Denny says

    December 4, 2017 at 10:26 pm

    Hi Diane,

    Is me again. I trying to do it again in a new company environment.

    This time, when i try to choose the script in the Rules, i can't find the any record there.

    Reply
    • Diane Poremsky says

      December 4, 2017 at 10:31 pm

      You can't find the script? Are you using the one with Sub SaveMessageAsPDF(Item As Outlook.mailItem) as the title? (It's at
      https://www.slipstick.com/files/run-a-script-rule-save-as-pdf.txt)

      Reply
  16. Bishwarup Dutta says

    December 4, 2017 at 6:54 am

    I get an error 'Method or data member not found' and
    Application.ActiveExplorer.Selection is highlighted

    Reply
    • Diane Poremsky says

      December 4, 2017 at 2:08 pm

      Do you have one or more messages selected? That error basically says it can't find email in the selection. Also, it needs to be actual email messages, not read receipts, NDRs, meeting requests etc.

      Reply
  17. Joe says

    December 1, 2017 at 12:54 am

    Hi Diane
    I have set the script version up to run automatically which is fine. But i have the first version on this page added as a macro and a button on the ribbon to run it. The button does nothing. Another button I've added using your macro to save attachments works fine. All these are signed by my own cert and macro security is set low as possible. What am i doing wrong? All i have changed is the location of the saving folder (which i also did successfully in the other two mentioned macros)

    Reply
    • Diane Poremsky says

      December 4, 2017 at 11:51 pm

      >> All i have changed is the location of the saving folder (which i also did successfully in the other two mentioned macros)
      Oh... make sure the path is correct.
      After this line, add another msgbox
      Set tmpFileName = your path 'FSO.GetSpecialFolder(2)
      msgbox tmpFileName

      and one after this
      tmpFileName = tmpFileName & "\" & sName & ".mht"
      msgbox tmpFileName

      Are the paths correct?

      Reply
      • Joe says

        December 5, 2017 at 12:13 am

        Thanks Diane
        I found another workaround - added in a click, and it has worked fine since SaveMessageAsPDF_Click()

  18. Jim Bo says

    December 1, 2017 at 12:50 am

    Thanks Diane
    Just one issue, i have got the automatic script one running fine. But i tried to ad the first one on this page as a macro then call it up with a button on the ribbon but it doesnt work? the button next to it - another of your macros - to save the attachments works fine, but when i click this it doesnt do anything. I have signed them all with my own cert and have macro setting on lowest available. Also when i run it from the editor it works a charm, just not from the button. Any clues?

    Reply
    • Diane Poremsky says

      December 4, 2017 at 11:49 pm

      it runs on a selection, so as long as a message is selected, it should work. Add msgbox "It's working" as the first line - i think you'll find the button is working but something else is not.

      You can also add a msgbox after this line to pop up the message subject. That will show that its getting into the loop.
      Set Item = obj
      msgbox item.subject

      Reply
  19. Richard says

    October 10, 2017 at 2:15 am

    A really great macro Diane

    Reply
  20. Kelvin says

    August 29, 2017 at 9:32 am

    Dear Diane,
    Thank you for sharing this VBA script. It is work and helpful. I have one issue that the PDF cannot show the full page, is there any way to solve it?

    Thanks

    Reply
    • Diane Poremsky says

      August 30, 2017 at 12:41 am

      is it not saving all of the pages or is the page scaled to the wrong size?

      Reply
      • Kelvin says

        August 30, 2017 at 8:17 pm

        it is saving all page,but the page size may be wrong. how to control it?
        for example:
        email content show:
        abcdefghijklmnopqrstuvwxyz
        123456789123456789123456
        after convert to pdf:
        abcdefghijklmnopqrst
        123456789123456789

      • Diane Poremsky says

        September 28, 2017 at 9:16 pm

        I don't believe you can control it in code, it uses the default settings for the application.

  21. Bharat Devana says

    March 25, 2017 at 11:07 am

    Hello,

    Thanks for the code. Its working like a charm. Is there a way that I can save the messages as .tif? Let me know.

    Reply
    • Diane Poremsky says

      March 25, 2017 at 11:26 pm

      if word can save as a tif, definitely, otherwise, it depends on the program you use to view tif's. it need to support vba control or command lines.

      Reply
      • Bharat Devana says

        March 26, 2017 at 12:32 pm

        I have MS Document Image writer as the tif printer. Is there a possibility to it and print the messages in Tif? Could you help with the code?

      • Diane Poremsky says

        April 2, 2017 at 9:13 am

        open word. if the Developer ribbon is not visible (2010 and up) enable it in file, options, customize ribbon. On the Developer tab, click the button to record a macro then save/print the document (probably a blank page - that's fine) as tif. stop the recorder and get the code for ExportAsFixedFormat - beginning at ExportFormat:=, replace it with the code to save as tif.

        if it's not using exportasfixed format, you may need to do more editing to the save block to make it work.

  22. Rob Anrtt says

    March 1, 2017 at 11:38 am

    Can this code be altered to save attachemnts as well?

    Reply
    • Diane Poremsky says

      April 2, 2017 at 9:06 am

      yes, you can add code to save the attachment, either before or after printing. Code samples showing how to save are here https://www.slipstick.com/developer/save-attachments-to-the-hard-drive/ and here https://www.outlook-tips.net/code-samples/save-and-delete-attachments/

      Reply
  23. Jacqueline says

    January 26, 2017 at 11:04 pm

    Dear Diane,

    I tried using your code in Excel VBA but I kept getting the error message, "Compile error: Can't find project or library" although I did set the reference to the Word object library in Tools > References.

    Any advice, please? Thanks.

    Reply
    • Diane Poremsky says

      March 20, 2017 at 1:18 am

      This code runs as an outlook macro - to run it from excel you also need to properly reference and call outlook object model.

      Reply
  24. joe says

    January 10, 2017 at 11:20 pm

    Hey Diane, I've been looking all over your site, but haven't found anything so i thought I'd just ask....do you have anything on how to access the acrobat add-in (if you have it) in order to save messages as pdf's? I am really hoping that I can access the add-in to do something like "oMail.SaveAs sPath & sName & ".pdf", olPDF" rather than using the Word work around?

    I haven't been able to find anything on this anywhere...

    Thanks,
    Joe

    Reply
    • Diane Poremsky says

      January 12, 2017 at 6:06 pm

      I'm not sure how much is exposed in the addin, but you might be able to call acrobat vba to print to it.

      Reply
  25. Stefan says

    November 9, 2016 at 4:34 am

    Dear Diane,
    you just saved me so much time and trouble writing such a skript myself.
    Thank you!
    Stefan

    Reply
  26. Michael Kulawig says

    November 9, 2016 at 2:16 am

    Dear Diane
    thank you for this nice piece of code, in one of the previous post a user asked for the option to open the "save as" dialog, did you find af solution for this ?

    greetings from Denmark
    Michael

    Reply
    • Diane Poremsky says

      November 9, 2016 at 9:10 am

      i don't have a code sample, but this page has some information - https://msdn.microsoft.com/en-us/library/aa219843(office.11).aspx

      Reply
  27. Martin V says

    November 1, 2016 at 5:53 am

    Hi everyone,

    Thank you for the code, this is some really good work here,

    I'm getting an error message though " Object required, with one of the first lines of code sName=Item.Subject,

    I can't understand why,

    any idea?

    Thanks a lot

    Reply
    • Diane Poremsky says

      November 9, 2016 at 9:13 am

      do you have one or more email messages selected?

      Reply
  28. Nate says

    September 20, 2016 at 3:06 pm

    Getting an error:

    Compile Error: User-defined type not defined.

    Then highlights this line "Dim wrdApp As Word.Application"

    Suggestions?

    Reply
    • Diane Poremsky says

      September 20, 2016 at 3:51 pm

      Did you set a reference to the Word object library in Tools > References?

      Reply
  29. Thierry says

    August 24, 2016 at 8:41 am

    Hello,
    I have one error : "Compile Error: Undefined variable"
    for : "tmpFileName "
    I have "Micorsoft Word 16.0 Object Livrary" and " Microsoft Scripting Runtime" are selected.
    Thanks,
    Thierry

    Reply
    • Diane Poremsky says

      August 24, 2016 at 10:07 am

      Add Dim tmpFileName as string at the top with the other Dim lines.

      Reply
  30. gerrit says

    June 9, 2016 at 2:30 pm

    This is a great post, but we are in need of removing the header information (from, to, subject, date info) so that the it would render the same way as opening an email in the browser and printing from there. Is there any way to modify this code to only include the body of the email? that would be a HUGE help. thanks

    Reply
    • Diane Poremsky says

      August 18, 2016 at 10:51 am

      Replace
      Item.SaveAs tmpFileName, olMHTML

      with these lines

      Dim ConvertHTML As Boolean
      ConvertHTML = True

      If Item.BodyFormat = olFormatHTML And AlwaysConvert = False Then
      Dim rawHTML As String
      rawHTML = Item.HTMLBody

      If CheckHTML = False Then
      ConvertHTML = False
      Else
      If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
      ConvertHTML = False
      End If
      End If
      End If
      If ConvertHTML = False Then
      Set objFile = FSO.CreateTextFile(tmpFileName, True)
      objFile.Write "" & rawHTML
      objFile.Close
      Set objFile = Nothing
      Else
      Item.SaveAs tmpFileName, olHTML
      End If

      Add these lines at the top of the macro
      Dim browser As String
      Dim AlwaysConvert As Boolean
      Dim CheckHTML As Boolean
      browser = "C:\Program Files\Internet Explorer\iexplore.exe"
      AlwaysConvert = False
      CheckHTML = True

      Reply
  31. Jay says

    May 21, 2016 at 9:31 am

    Hi Diane
    First, let me thank you for this post and in helping 'confused.com' people like me.
    I work for academic bureau and we have the habit to save pdf file of all correspondences sent to sponsors abroad. However, I thought to ask you of the possibility in using your Macro in converting old e.mails/attachments to a specific desktop folder all at once.
    Sorry if my query is irrelevant ..!

    Reply
    • Diane Poremsky says

      August 18, 2016 at 12:47 am

      The first macro works with the selected messages - can be one or more messages.

      Reply
  32. Bill Shannon says

    April 15, 2016 at 9:58 am

    Brilliant.
    We have a document imaging system that allows us to import TIFF and PDF documents. Currently our incoming faxes are stored in a network share and are imported routinely by our scanning department.
    Using this script we'll be able to catch more communication by implementing it to the senior staff. With a few modifications they'll be able to store an entire email thread to the same network share and will be imported as part of our pre-existing routine.
    I did add a few extra lines in so that I can grab the users login name and stuff it in the title of the resulting PDF. Helps the scanning department to determine where to put the documents.

    Again, thanks so much for this code!

    Reply
  33. Don says

    April 8, 2016 at 4:53 am

    How can this code be modified to send only the header contents of the email:?
    From:
    To:
    Date:
    Subject:

    wrdApp.ActiveDocument.ExportAsFixedFormat

    Many thanks,
    Don

    Reply
  34. Don says

    April 5, 2016 at 11:35 am

    Hi Diane,

    I am glad I found your website. It is partly what I was looking for :-)
    I have a requirement which seems difficult to me. I will explain it as below:

    We have a system which picks up the .pdf file from the email and uploads it in a system. We would like to have a macro, where the email body is appended at the end of the invoice pdf attachment.

    This macro checks if there is a .pdf attachment in the email.
    If yes then
    Copy the contents of the email body
    Paste it at the end of the attached pdf file
    Save the pdf attachment of the email
    Save the email.

    So that when our system uploads this pdf it contains the actual invoice details and also also the email body in the file.

    Diane, is this possible and how can this be done?

    Many thanks for your reply. Looking forward to hearing from you.

    Best regards,
    Don

    Reply
    • Diane Poremsky says

      April 8, 2016 at 11:42 am

      This part > Paste it at the end of the attached pdf file is the hard part. You need to use a pdf editor that can be controlled by VBA. It might work in Word, provided it does not mess up the PDF formatting. (I have some PDFs that look awful in Word.) Adobe Acrobat supports VBA but I've only used it for simple things, like printing, and have no idea how to do it using Acrobat.

      Reply
    • Ashley says

      April 11, 2016 at 7:48 pm

      Would you/your users all have access to Acrobat?

      I spent a couple weeks fiddling with this code and using it to do something similar. I save the e-mail as a PDF, then save all of the attachments, convert them to PDFs if they aren't already (using VBA+acrobat), then attach the attachments at the end of the e-mail PDF.

      Depending on how your macro picks up the attachment and interacts with your system, my code could potentially work for you..
      Would your system be able to detect/pick up a file that was saved and combined in the temp folder (or any other windows folder) and THEN upload it, rather than trying to do it all without leaving outlook?

      Reply
      • Olivia says

        December 9, 2016 at 12:47 pm

        Do you have a code for this? I need to download about 6,000 emails, all with multiple attachments and make each email with it's attachments into one pdf. I'm looking for a code that I can just run once on the folder containing all of the emails. I have access to acrobat for this

      • Diane Poremsky says

        January 12, 2017 at 6:31 pm

        No, i don't currently have code that turns both the email and the attachment into a pdf. Adobe Acrobat has an addin that can do it - they have a free trial so you can see if it meets your needs. I'm not sure if any other pdf programs have a similar feature but its worth checking out.

      • Rajesh Chawda says

        March 26, 2018 at 11:37 pm

        As written by you that Adobe Acrobat has an addin that can turn both the email and the attachment into a pdf -
        my query is that if we have hundreds of such pdf emails (each having another pdf as an attachment to the email ( in other words a pdf embedded in another pdf ), then
        Can a VBA macro code help in opening the embedded pdf document (from the pdf email) to extract some information ?
        Would you have some readymade vba code to do so?
        OR Can you guide some link where such a similar code is shared ?
        I am required to do this for hundreds of emails every week, which eats away more than 6-7 valuable hours every week.

      • Diane Poremsky says

        March 29, 2018 at 11:44 am

        I don't have any code that will open it, but it may be possible as long as you use Acrobat.

        Keep in mind that when you create a package, the attachment is just another page in the pdf, which could make it easier to access using code.

  35. Michael says

    December 31, 2015 at 11:09 pm

    Hi Diane,

    Thanks for this. It works great and this is going to save me a lot of time in the future. Right now, the script saves the files to my Documents folder. Would it be possible for me to create a special file in Documents, and then have all of files saved to that discreet folder?

    Thanks in advance.

    Reply
    • Diane Poremsky says

      March 23, 2016 at 2:26 pm

      Sorry I missed this before - sure you can change it. These lines set the path:
      MyDocs = WshShell.SpecialFolders(16)
      strToSaveAs = MyDocs & "\" & sName & ".pdf"

      just add the folder name to it
      strToSaveAs = MyDocs & "\newfolder\" & sName & ".pdf"

      if it's not under my docs, use the full pATH:
      strToSaveAs = "D:\my stuff\folder\" & sName & ".pdf"

      Reply
  36. GVB says

    October 29, 2015 at 11:35 am

    Hello, Thanks for the code. IO converts the email message, I would like to know how to convert to pdf along with the attachments.

    Thanks in advance.

    Reply
    • Diane Poremsky says

      October 30, 2015 at 9:55 am

      What file type are the attachments? Outlook needs to open the attachment then control the application to save as pdf or print to pdf. I have some code samples at print attachments as they arrive that show how to send attachments to the printer. It will create separate files though - if you want one file it would be more efficient to use an addin.

      Reply
      • Diane Poremsky says

        October 30, 2015 at 9:57 am

        Print Email (and Attachments) on Arrival has a list of utilities that can print messages and attachments.

  37. Matt O'Brien says

    October 5, 2015 at 3:35 pm

    A temp file is stored in ........AppData\Local\Temp.

    I am getting file exists errors .......

    Should these temp files be cleared by some method.

    (Ps... Thanks for a brilliant piece of code..... a really brilliant piece of code)

    Reply
    • Diane Poremsky says

      October 10, 2015 at 10:57 pm

      Type %temp% in the address bar of windows explorer and press enter to open the temp location then delete the files.

      Reply
  38. Michele says

    October 1, 2015 at 9:32 am

    Hi Diane,

    I receive an "unable to save the file ... mht" "the file is already open"
    How can I fix?
    Thank you

    Reply
    • Diane Poremsky says

      October 10, 2015 at 11:42 pm

      Is it open in IE? I think that is the only program that can read mht files.

      Reply
    • Mike says

      September 15, 2016 at 3:45 pm

      Check file name length. I run into this issue when my subject line is extremely long. To fix it, I updated the following:
      sName = Item.Subject
      to
      sName = Mid(Item.Subject, 1, 20) & "-" & Format(Item.SentOn, "yyyy-mm-dd")

      Adjust the desired length from 20 to whatever you like.

      Reply
  39. Denny says

    August 24, 2015 at 4:36 am

    Hi Diane,

    Thanks for your guidance, the rules and script work perfectly.

    Just a little more request, can i make the file name more meaningful as in the file name able to capture certain keywords from the email content?

    Reply
    • Diane Poremsky says

      August 24, 2015 at 12:05 pm

      The filename is set here -
      sName = Item.Subject

      it can use any field in the email - if you want to grab words from the body, you'd need to use instr or regex.

      If you have a specific set of unique words to look for, I'd probably use an array. Using the first sample at https://www.slipstick.com/developer/using-arrays-outlook-macros/, change the if line to
      If InStr(LCase(Item.body), arrCat(i)) Then sname = arrCat(i)

      When a keyword is matched, it uses it in the filename (can add it to the filename: sname = arrcat(i) & item.subject).

      the big thing is the keywords need to be unique.

      If you are looking for something that will be preceded by specific text and will vary with each message, like
      Name: Bill Smith
      you'll use regex to find the text and keyword.
      Regex sample: https://www.slipstick.com/developer/regex-parse-message-text/

      Reply
      • Tiffany says

        July 27, 2016 at 2:30 pm

        Is there a way to add just the sent date without the time? I used the Item.SentOn and got everything when I really just want the received date.

      • Diane Poremsky says

        July 27, 2016 at 2:46 pm

        use format( Item.SentOn, "yyyy-mm-dd")

        you can use pretty much any date format you want - the number (1, 2, or 4) of y's, m's, and d's are what matters.

  40. Albert says

    August 20, 2015 at 3:44 pm

    It's in the first paragraph of thread: (There is a third way: use Adobe Acrobat's package feature. It makes a really nice PDF archive, if you own Acrobat.)

    Reply
    • Diane Poremsky says

      August 20, 2015 at 4:11 pm

      Oh - that is built into Acrobat - when the Acrobat addin is enabled, there will be a menu to create a PDF package, which is a collection of individual pdf files. It's great for creating an archive. It saves the selected messages and any attachments bundled together as individual pdf's with in one big pdf file. Selecting a bunch of messages and printing them as PDF creates one big PDF - a package creates individual pdf's within a big pdf.

      Reply
  41. Albert says

    August 20, 2015 at 2:01 pm

    Hi Diane,
    You mentioned there was a third option regarding the Adobe Acrobat feature. Can you provide more details?

    Reply
    • Diane Poremsky says

      August 20, 2015 at 3:31 pm

      Sorry, I don't recall in what context I said it and don't see it in a quick look over the comments.

      Reply
  42. Denny says

    July 27, 2015 at 11:15 pm

    Hi Diane,

    I have another problem with the script again. At first, it was works well for the first time. The next day, after i reboot my system, the script is no longer working. The rules is still there.

    There is no error message. It just can't save the email to the folder.

    Please advice is there any troubleshooting method?

    Thanks.

    Reply
    • Diane Poremsky says

      July 28, 2015 at 12:18 am

      Is macro security set to low / none? That is the usual reason why scripts aren't working.

      Reply
  43. Denny says

    July 14, 2015 at 1:45 am

    Hi Diane,

    What should i do after go in to the references window? I totally know nuts on VBA.

    Thanks in advance.

    Reply
    • Diane Poremsky says

      July 14, 2015 at 9:50 am

      Locate Microsoft Word version.0 Object Library on the list and check it. If you have more than one listed, choose the one that is the same version as Outlook - usually the higher number. I added a screenshot of the dialog to the page.

      Reply
  44. Denny says

    July 13, 2015 at 9:36 pm

    Hi,

    I'm a noob in scripting.

    I just copy and paste your comman and create the outlook rule.

    When i trigger the rule, it the VBA will have compile error: User-defined type not defined.

    Reply
    • Diane Poremsky says

      July 14, 2015 at 1:07 am

      Forgetting to do this will cause that error:
      Don't forget to set a reference to the Word object library in Tools > References.

      Reply
  45. Albert says

    March 18, 2015 at 2:37 pm

    Hi Diane,
    Using the script mentioned above, where is the converted file saved at?

    Regards,
    Albert

    Reply
    • Diane Poremsky says

      March 18, 2015 at 3:51 pm

      These lines control that:
      MyDocs = WshShell.SpecialFolders(16)
      strToSaveAs = MyDocs & "\" & sName & ".pdf"
      Specialfolders(16) is the user's Documents folder.

      Reply
  46. Ed van den Bogaard says

    March 13, 2015 at 7:25 am

    Removing the "as object" parts solved the problem.

    Just out of curiosity: because tmpFileName and MyDocs are not dimmed in your code, I wonder if the issue I ran into is because of the different language version I use?

    Thanks and regards,
    Ed

    Reply
    • Diane Poremsky says

      March 13, 2015 at 11:42 pm

      i dont think your language has an affect. its good form to declare everything but its not always required.

      Reply
  47. Ed van den Bogaard says

    March 10, 2015 at 11:26 am

    Hi Diane,

    The macro doesn't work in my Outlook 2010 (32 bit) on Windows 7 (64 bit). Both Outlook and Windows 7 are Dutch language versions.

    First I get the error that tmpFileName and MyDocs are not defined as variables.

    After insert
    Dim tmpFileName As Object
    Dim MyDocs As Object

    the macro gives an "error 450" on the line
    tmpFileName = tmpFileName & "\" & sName & ".mht"

    Any idea what's causing the trouble?

    Regards,
    Ed van den Bogaard

    Reply
    • Diane Poremsky says

      March 11, 2015 at 9:01 am

      They should be dimmed as string, not object. Either change it to string, or remove the as object part.

      Reply
  48. Richard Wilde says

    February 25, 2015 at 1:49 am

    Hi Diane, I assume this will work with outlook 2013 (365). My use case is to run a rule as an email comes in (can see from comments how this is possible) then save as PDF to disk then I would need to send this pdf as an attachment with the original email subject

    Possible?
    Thanks, great article by the way

    Reply
    • Diane Poremsky says

      March 11, 2015 at 8:59 am

      It will work with Outlook 2013/365.

      Reply
  49. Rafael says

    January 14, 2015 at 1:54 pm

    Hello Diane - is there any way to have the user pick the file name, if so, can the save as dialog open to a preset folder?

    Reply
    • Diane Poremsky says

      January 21, 2015 at 12:37 am

      you need to call the open/save dialog. I'll see if i can find a code sample that does that.

      Reply
  50. Eugene says

    December 1, 2014 at 11:35 am

    Hello Diane,

    I would like to save only 1st page of email and rename the file based on information found in the body of the text (SWIFT MT103). I have the following information in the email body.

    "...
    :32A:141128USD100000,00
    ...
    "
    [Value Date/Currency/Amount]
    [YY MM DD CURR Amount]

    I want to save the PDF file as "28112014" [DDMMYYYY]
    If you could help adjust the code to get the email saved and renamed would be greatly appreciated.
    Thanks,
    Eugene

    Reply
    • Diane Poremsky says

      December 16, 2014 at 11:37 pm

      First page is easy: From:=1, To:=1,
      Grabbing the date out requires regex. Samples are here: https://www.slipstick.com/developer/regex-parse-message-text/

      All you need is a pattern to search for - this might work if the date is always 6 digits.
      .Pattern = "[:](\w*)[:](\d){6}(\w*)" should = :32A:141128USD and M.SubMatches(1) should get just the date.

      Reply
  51. Eugene says

    November 28, 2014 at 11:34 am

    Hello Diane,
    Thanks for the code. Is there a way to save only the 1st page of the email?

    Many thanks

    Reply
    • Diane Poremsky says

      December 16, 2014 at 11:24 pm

      if you want to save only the first page of the message as a pdf, in this macro (which uses word to save the pdf), you would change From:=0, To:=0, to From:=1, To:=1,.

      Reply
  52. Dejan says

    November 20, 2014 at 1:24 pm

    Hello Diane,

    Is there a vba code to save .msg to .pdf, i have a code where it will extract e-mail from outlook and put it into a folder as .msg, I need vba code to convert it to .pdf, also I have a full version of adobe.

    Thank you

    Reply
    • Diane Poremsky says

      November 20, 2014 at 4:05 pm

      I have a code sample here - https://www.slipstick.com/developer/code-samples/save-outlook-email-pdf/

      Reply
  53. themetalfox says

    November 5, 2014 at 8:46 am

    Hi Diane

    Do you have an 'out of the box' Outlook 2013 script that can do the following for all emails in a certain folder?

    Create a forwarded message
    Delete all email addresses from text before forwarding
    Delete any email signature before forwarding
    Delete all hyperlinks completely before forwarding
    Delete any text string beginning with http before forwarding
    Forward email to a specific email address

    I literally have hundreds of emails a day I have to forward but currently I have to forward these manually as for security reasons I have to manually delete all hyperlinks (including the text for the hyperlink itself) and email addresses. A script that does the above would be a legitimate godsend as I do not know how to code at all.

    Hope you can help?

    Reply
    • Diane Poremsky says

      November 7, 2014 at 12:19 am

      I don't have any that do all that -
      #1/6 are simple (have code)
      #2 can be more difficult - i might have code that can be tweaked to do it.
      #3 if there is a way to define the signature - such as using "-- " to mark where it begins, yes. If the signature block is not defined, it's more difficult.
      #4 difficult, not impossible. I don't think i have any code samples but word code to remove hyperlinks should work.
      #5 a regex should do it.

      Reply
  54. Carrie Kelly says

    October 13, 2014 at 12:21 pm

    Diane,

    How would I change the title the .pdf is saved with?

    The current email is titled CM FML Not 0000000

    I would like to save the title as 00000000_FMLDOC_yyyyddmmhhss

    Any thoughts on how I can do that with this code?

    Reply
    • Diane Poremsky says

      October 13, 2014 at 10:30 pm

      The name is set using this code:
      sName = Item.Subject
      ReplaceCharsForFileName sName, "-"

      so you'd change the sName string. the date is set using Format(item.receivedtime, "yyyddmmhhss"). if the format is always 2 characters, space, 3 characters, space, digits, you can use instr, mid, and other functions to put it together.

      FML: strdoc = mid(sName, 3,3)
      0000's: strCode = right(sName, 7)

      put that together for the subject:
      strCode & "_" & strdoc & "DOC_" & strDate

      if the strCode section length varies, you need to use mid and len to get it.

      Reply
  55. Renee SIms says

    October 10, 2014 at 10:07 pm

    Can I change the My Docs in this code to save the email message to the same place I'm saving the attachments too? (from your other example)?

    Reply
    • Diane Poremsky says

      October 10, 2014 at 10:18 pm

      Yes, you can. The only thing that matters is that strToSaveAs is a valid path. How you get there is not important.

      Reply
  56. phan says

    September 24, 2014 at 9:37 pm

    Is there a way rename the file if it exist to add (1), (2) .... at the end instead adding the time and date?

    Thanks,

    Reply
    • Diane Poremsky says

      September 24, 2014 at 10:06 pm

      Yes, you'd use sName = sName & "(" & i & ")" to set the name. There are three options for numbering:
      consecutive numbers for each attachment in a message. It resets to 1 with each message.
      consecutive numbers during an outlook session - resets when outlook is closed and reopens.
      consecutive numbers forever - use either a text file or registry to increment the number and pick up the next number after restarting or rebooting.

      A sample using the registry is at https://www.poremsky.com/office/sequential-numbers-random-character-keywords/ - the text file method is at VBOffice.net and linked from that page.

      To change restart at 1 when you restart outlook, use
      Dim i as Long at the top of the page (outside of the macro)
      then use
      i = i + 1
      before the filename is set.

      Reply
  57. richbmar says

    September 15, 2014 at 8:56 am

    Hi Diane, Thanks for the script version. It works very well. Would it be possible to delete the message from Outlook once the message is saved as a pdf? I am running the script from a rule on messages that do not have attachments. I would be very efficient if I could delete them automatically once they are saved as a .pdf.
    (I am also very interested in a script that would save both the message and an associated attachment)
    Regards,

    Reply
    • Diane Poremsky says

      September 16, 2014 at 10:34 pm

      You could delete the message - at the end, before Next obj, add item.delete

      Reply
  58. Wayne says

    September 5, 2014 at 5:13 am

    Very useful. What line do I need to modify to change the save location, to say 'D:\Save'

    Reply
    • Diane Poremsky says

      September 5, 2014 at 7:58 am

      These lines do the save:
      MyDocs = WshShell.SpecialFolders(16)
      strToSaveAs = MyDocs & "\" & sName & ".pdf"

      So change MyDocs to "D:\Save" - this ensures that anything to uses the MyDocs variable will have the correct path. If nothing else uses it, you could change strtoSaveas to "D:\Save\" & sName & ".pdf"

      Reply
  59. anthony houston says

    August 11, 2014 at 5:13 pm

    I have been able to use this code successfully. I was wondering if it is possible to implement some additional code in the "Create a word object" portion. For instance, I need to delete the header (list of emails) so i tried implementing some code to delete them, but no success. Tried adding the following to delete the first 18 lines:

    Selection.MoveDown Unit:=wdLine, Count:=18, Extend:=wdExtend
    Selection.Delete Unit:=wdCharacter, Count:=1

    Reply
    • Diane Poremsky says

      September 1, 2014 at 1:52 pm

      It is possible, but you need to call the inspector. This macro has the basics - https://www.slipstick.com/developer/word-macro-apply-formatting-outlook-email/ - then you can use movedown and delete.

      Reply
  60. Mike says

    July 22, 2014 at 11:07 am

    Hi, its okay the windows finally appears in front of the windows. Now, i would like to know if its possible to save the email into the desktop instead of the documents.

    Thank you very much you make it easier for me !! :)

    Reply
    • Diane Poremsky says

      July 22, 2014 at 3:13 pm

      That would be changed in SpecialFolders(16) - try SpecialFolders(10) for desktop.

      Reply
  61. Mike says

    July 22, 2014 at 8:01 am

    I run it from a button that i've installed in the ribbon.

    Its supposed to work by there ? By the way thank you for answering me ! :)

    Reply
    • Diane Poremsky says

      July 22, 2014 at 8:45 am

      Normally when you use a button, any dialog comes up on top. Actually, the macro saves it using the subject name in My Documents - you changed it to bring up the dialog. What code are you using to bring up the Save as dialog?

      When I use browseforfolder function and replace the mydocs line with this:
      MyDocs = WshShell.SpecialFolders(16)
      MyDocs = BrowseForFolder("C:\Users\diane\documents\")

      the dialog comes up on top.

      Reply
  62. Dave says

    May 22, 2014 at 4:46 pm

    Save the email and all the attachments as a single PDF.

    Reply
    • Diane Poremsky says

      May 22, 2014 at 7:54 pm

      I'll see if i can put something together.

      Reply
      • Bruce says

        June 10, 2014 at 10:59 am

        That would be great to have this. I am looking for something similar as well. Thanks!

      • Mike says

        July 21, 2014 at 2:15 pm

        Hi, when I execute this macro the windows of "save as" is behind the other windows, can we use the Z-Order or Z-Indez command here ?

      • Diane Poremsky says

        July 22, 2014 at 1:09 am

        Are you running it from the VBA editor or using a button on the ribbon or the Macros list on the Developer tab? It should only come up in the background if you run it from the VBA Editor.

      • ahecht says

        August 31, 2014 at 2:45 pm

        Were you able to create a script that includes the message and any attachments in a single pdf?

      • Diane Poremsky says

        September 1, 2014 at 1:53 pm

        No, I haven't been able to get it working.

      • Diane Poremsky says

        September 2, 2014 at 12:01 am

        I think what we need to do is print to pdf and include the attachment in the same print...

  63. Dave says

    May 20, 2014 at 2:23 am

    Hi Diane

    This macro only exports the email contents and not the attachments.

    Do you think it's possible to expand this macro to include a copy of the attachments as well into the same file?

    Reply
    • Diane Poremsky says

      May 22, 2014 at 2:46 pm

      I swear I replied to this earlier. :( Yes, you could. Do you want to print the attachment as a pdf or just save it with the pdf?

      Reply
  64. Jules says

    April 4, 2014 at 7:50 am

    I've copied across the code and inserted to Module 4 as a macro.
    It is not visible int the Macro selector
    All in accordance with May 10 2013 link nad made sure the name header was correct.
    Definitely user error my end I'm sure.

    Regards,

    Reply
    • Diane Poremsky says

      April 4, 2014 at 11:40 am

      This line: Sub SaveMessageAsPDF(Item As Outlook.mailItem) means it only runs from another macro or a rule, it won't be listed in the macros list. If you run it manually (ie, from the macros list) you need to use the macro on the page.

      Reply
  65. Jules says

    April 2, 2014 at 3:57 pm

    Diane, I've tried to use the outlook macro but with no luck.

    I've copied the vba from the link but it is not visible in Macros.

    Any assistance appreciated.

    Reply
    • Diane Poremsky says

      April 3, 2014 at 9:05 am

      Did it have a name - Sub SaveMessageAsPDF()? I just noticed that was missing from the code. To run it manually, you'll use a name in that format. To run it from another macro (or in a rule) you'd use Sub SaveMessageAsPDF(Item As Outlook.mailItem) format for the name.

      Reply
  66. Adam says

    July 23, 2013 at 6:39 am

    Hi,

    I wonder if it'd be possible to have this code run as a rule, but save as a .txt rather than a .pdf. This would presumably cut out the steps to open MS Word making the code a tad more simple?

    I can't believe this functionality isn't built into Outlook as standard. It's a good job there are people like you providing the average user with some help.

    Reply
    • Diane Poremsky says

      July 23, 2013 at 9:02 am

      I have a code sample for text - Save email message as text file.

      to use it in a rule, change the sub title to
      Sub SaveMailAsFile(Item As Outlook.mailItem)

      and change oMail to item in the code.

      Reply
  67. Javier says

    July 2, 2013 at 11:34 am

    Dear Diane:

    Your script is very very useful. Thank you very much for sharing.

    If you allow me i would like to make a suggestion:
    - The reason why the script is slow is because every iteration the Word Object is created and destroyed.
    - Move the word object creation and destroy out of the loop. This way it will only create it once and re-use it for each file. That will improve the performance drastically.

    Best regards.

    Reply
  68. Dustin Weld says

    May 10, 2013 at 8:56 am

    Can this MACRO be changed to run as a script so that it can be used in Outlook Rules?

    Reply
    • Diane Poremsky says

      May 10, 2013 at 11:33 am

      Yes, it can be changed. Start with the name:
      Sub SaveMessageAsPDF(Item As Outlook.mailItem)

      Then remove the first 6 lines (3 dim, 2 set, For...) and the last 4 (Next obj and 3 Set's).

      I posted a text file with the corrected code here

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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

Latest EMO: Vol. 31 Issue 7

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
  • Disable "Always ask before opening" Dialog
  • This operation has been cancelled due to restrictions
  • Change Outlook's Programmatic Access Options
  • How to Hide or Delete Outlook's Default Folders
  • Use Public Folders In new Outlook
  • Removing Suggested Accounts in New Outlook
  • How to Delete Stuck Read Receipts
  • Sync Issues and Errors with Gmail and Yahoo accounts
  • Error Opening iCloud Appointments in Classic Outlook
  • 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
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

Sync Issues and Errors with Gmail and Yahoo accounts

Error Opening iCloud Appointments in Classic Outlook

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

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 © 2026 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.