Enhancing the Save Attachments Outlook Macro

Update: Feb. 28, 2007: Due to numerous requests I’ve created a branch of this macro that saves attachments for all messages / calendar items, selected or not. To see it, please see my post http://arcanecode.wordpress.com/2007/02/28/saving-all-attachments-in-outlook/ or http://shrinkster.com/mhn. There I have uploaded a new file with both the macro below and the new one that saves all items, selected or not.

Yesterday I blogged about a macro I wrote for my wife to allow her to save attachments for multiple messages in Outlook. After using it today she asked for a few enhancements. First, she wanted to be able to select the directory to save the attachments to. Second, she wanted the macro to detect that a file already existed, and allow her to rename the new file or skip it.

To accomplish the first item, I found a handy routine in a google groups thread. I’ll let you read it for yourself, the code is about half way down in a message by Joe Earnest, and can be found at http://shrinkster.com/l0v. I took Joe’s code and created a function out of it called GetOutputDirectory. I made one enhancement, at the end I make sure the output directory ends in a backslash.

For the second enhancement I used the good old scripting runtime library. Use the Tools, References menu in the VBScript editor and set a reference to the “Microsoft Scripting Runtime”, scrrun.dll. Rather than reposting all the code I’ve put the entire macro in a txt file you can download here: http://arcanecode.files.wordpress.com/2007/01/saveattachments2.txt

Here is the heart of the code

fileExists = fso.fileExists(outputDir + outputFile)

Do While fileExists = True
outputFile = InputBox(“The file ” + outputFile _
+ ” already exists in the destination directory of ” _
+ outputDir + “. Please enter a new name, or hit cancel to skip this one file.”, “File Exists”, outputFile)
‘If user hit cancel
If outputFile = “” Then
‘Exit leaving fileexists true. That will be a flag not to write the file
Exit Do
End If
fileExists = fso.fileExists(outputDir + outputFile)
Loop

‘Save it to disk
If fileExists = False Then
att.SaveAsFile (outputDir + outputFile)
AttTotal = AttTotal + 1
End If

As you can see, I check to see if the file exists and store that in a variable. I then enter a loop if the file exists, ask for a new name, then check to see if the new name exists. I stay in the loop as long as it does.

Should the user click the cancel button on the input box, I exit the loop prematurely and use the fileexists as a flag to write or not write the file.

There you go, an enhanced version of the SaveAttachments macro. Take a look at the full file I’ve uploaded, and leave a comment with any questions.

39 Responses to “Enhancing the Save Attachments Outlook Macro”

  1. Scott Says:

    Wonderful script! One question though, I am attempting to use this to clear the attachments from my calendar. It seems to only work on the days I highlight. Is there a way to get it to remove all attachments in the calendar just by selecting the calendar in the folder view? Again, it seems I have to select each day individually.

  2. arcanecode Says:

    Instead of cycling through the collection of selected items (the for cnt = 1 to Sel.Count area) you’ll want to cycle through the calendar folder. I’ll have to dig a bit to get the exact code, meanwhile you could always just do a Ctrl+A (Edit, Select All on the menu) to select all the items then run the script.

    I wrote the macro as a Christmas present to my wife, who wanted to save only messages she had selected, hence the way it was written.

  3. Scott Says:

    Thank you for your time with this, I really appreciate it.

    Unfortunatelly, CTRL+A doesnt work in the calendar. (I actually tried all variations prior to bugging you!) :-)

    Dont kill yourself, but if you could come up with something it would be wonderful.

    Thanks Again!

  4. Julie van Niekerk Says:

    Just wanted to thank you for an extremely useful piece of code. I get dozens of attachments from many of my writers every day, and having to save each message’s attachments individually has been time-consuming. One program I found did work well, but of course, was not free. Your macro works great. Thanks!

    Julie

  5. Saving All Attachments in Outlook « Arcane Code Says:

    [...] Posted by arcanecode in Outlook, VBScript, Development. trackback Back on January 3’rd, 2007 (http://arcanecode.wordpress.com/2007/01/03/enhancing-the-save-attachments-outlook-macro/ or http://shrinkster.com/mhm) I posted a useful macro that would save attachments on the selected [...]

  6. Dave Says:

    This is a brilliant bit of code. so useful i get loads of attachments which i want to save.

    I have messsages with attachments which have been forwarded, some times the file i want is 4 or more messages in. it saves the .msg file and not the jpg file i want. if there anyway aound this ?

  7. Danie Says:

    Hi There

    Thanks for the brilliant piece of code!.
    I have however one question as I would like to save the attachments to a network share, but if I change the destination folder to \\server\sharename then it says unable to save attachments even though everyone can save to the folder. Any ideas please?

  8. Troy Says:

    Great bit of code – thanks!
    Just a thought – I edited it to prefix the attachment with the subject of the email so that attachments will get similar names. I also had to filter out invalid characters.

    :)

  9. rujirek Says:

    Helpful site – thanks.

    I don’t supposed there’s a way to append the attachment to the existing file? after you checked if file already exists.

    Any suggestion would be greatly appreciated.

  10. Kenneth Darling Soerensen Says:

    Just the code I have been looking for – thanks!

    Unfortunately, I get an error when running the macro: “Compile error: User-defined type not defined” when the code reaches “Dim fso As FileSystemObject”

    Any idea why?

    Thanks in advance!

  11. dirk Says:

    @ Kenneth:

    In the VB editor in Outlook, under the ‘extra’ menu, there should be something like a ‘references’ option.
    Scroll through the list until you find “Microsoft Scripting Runtime”.

    • jo Says:

      In Office 07 (Professional?) the ‘References…’ otion is in the ‘Tools’ menu, for those who can’t find the ‘extra’ menu.
      Great Code!

  12. Sam Says:

    From a salesguy with no coding experience. Can some one please post step by step Install or Implementation instructions? Thanks for your help this looks like what I need. I have 400+ emails with .jpg atttachments that I need to extract and post on my website. Any reco’s are appreciated.

    Thanks!

  13. James Says:

    Very nice script! Thanks for making it available

    Sam, to install this macro open Outlook, click Tools – Macro – Visual Basic Editor. From there, click Insert New Module. Copy and Paste the script into the blank module that opens. Then click Tools – References and choose Microsoft Windows Scripting. Finally, click save.

    To run it click Tools – Macro – Macros, or hit Alt-F8 to bring up the macros window.

  14. Simon C Says:

    If i can get this to work it will save me about an hour every day, but I get the
    “Compile error: User-defined type not defined” when the code reaches “Dim fso As FileSystemObject” problem.
    When i go to the references menu on the vb editor there isn’t a microsoft scripting runtime or a microsoft windows scripting option.
    I’m using outlook 2003 with no disabled items.

  15. arcanecode Says:

    Simon: Check the paragraph right before the code. You will need to set a reference to the scripting runtime library, which is likely why you are getting the error.

  16. Tom Jacobs Says:

    Thanks for sharing!

    One question: I would like to use the macro to detach the images my webcam sends to my email adress every 10 minutes. The webcam always uses the same file name, and I would like to use the date/time of the image as (part of) the new file name.
    Is there any way I can get hold of those properties of the attached image file? Or any other way that would make the images distinguishable?
    Suggestions greatly appreciated!

  17. James Says:

    Cheers for the great script.

    WOuld like to know how to change the email folder if you don’t want the Inbox as the default folder to get the attachments from eg i have a rule to place orders from the inbox into the orders folder in outlook. Tried and failed to get it to work.

  18. Sandeep Says:

    Like to know the coding for if we forgot to Mention Cc some one? Please advise or mail me to sandeep_goyal01@infosys.com

  19. Marrisa Says:

    Thank you for the script, it was exactly what I needed.

  20. Iqbal Y. Says:

    Thanks to you and your dad (for buying the TRS-80).
    Code worked for me on the first try. You rock!

  21. Sven Says:

    Thanks a million, have been looking for this for days!

  22. BTD Says:

    Wonderful macro; extremely helpful. I’m not a VBA coder, but I would like to save my attachments with the date/time stamp of the message. For example, if the message containing the attachments was received on 01/12/2009 at 10:00 am, I would like each attachment’s filename to appear as follows: FILENAME_20080112.1000.EXT.

    Would you be able to help me with the necessary code to implement this change to the macro? Thanks very much.

    • GIB Says:

      BTD,

      Did you get a response or figure out how to incorporate the date/time stamp when saving the attachments? I am in need of the same modification as I receive system generated reports only distinguished by the time stamp.

      GIB

  23. Jeff Says:

    I love the code. I wrote something similar. What I am trying to get mine to do is print the attachments (I’d like it to convert all files to .pdf, and the only way I know how is to print them using a convert to .pdf printer).

    Do you know how to tell VB to open, print, and close any file in that order?

  24. Jeff Says:

    Oh, almost forgot…

    Thanks!

  25. Jeremy Says:

    Hello,

    I need help if anyone knows how to accomplish this. I receive an email which contains two attachments. Each attachment has the name of a city in it (88552_virginia.pdf) and (77558_calhoun.pdf). I need to rename & save each of the attachments into their own folder. Some how the script would need look for the name in the attachment then save to a folder based on the name of the attachment. I need to rename each file as ad.pdf and place them in two separate folders. Then I have an ftp program that automatically uploads the file to a website from that point.

    Summary:

    2 email attachments in one email (88552_virginia.pdf) and (77558_calhoun.pdf).

    The script needs to pick out the name of the attachment by looking for “virginia” or “calhoun” and save each to their own folder with a rename to ad.pdf

    My folders would be
    /virginia/ads/
    /calhoun/ads/

    I greatly appreciate any help. Thanks!

  26. Jake Says:

    Wonerful! Thank you very much!

  27. Ben Says:

    Great script, perfect, just what i need!

    Thank you.

  28. Heartburn Home Remedy Says:

    This is very hot info. I think I’ll share it on Digg.

  29. Anthony Says:

    Works great. This is awesome. Thanks for sharing.

  30. Genaro Says:

    You rock man, thanks it really helped me a lot.

  31. Rina Says:

    Brilliant!

  32. TDJ Says:

    To all that want to save files in a non-standard way (example: with date stamping, in special dirs etc).

    You need to change the outputFile, possibly the outputDir in the line

    outputFile = att.FileName

    Example: if outputFile = “attach01.jpg” and you want “attach01_2007-03-19_02-24-25.jpg”, all you need to do is some string manipulation.

    If you define a new variable as “MailItem” you can use
    set mailitemvar = sel.item(cnt)

    Then it’s easy to access the properties for sel.item(cnt). Example: ReceivedTime. You can format as per standard VBA using format().

  33. TDJ Says:

    you may want to include the “MakeDirStructure” function found at http://www.visualbasic.happycodings.com/Files_Directories_Drives/code13.html

    That way it’s quite simple to save in a structured way, example

    outdir\sender\date\filename.ext

    or
    outdir\yyyy\mm\dd\filename.ext

    just include makedir(outdir+ yoursubstructure) somewhere.

  34. Dennis Says:

    Great script! Thanks for sharing.

  35. TD Says:

    Exactly what I needed. Worked perfectly.
    Would have been nice if it remembered the last directory I saved the files to, but other than that it’s excellent. Great work!

  36. iko Says:

    i used u work in my plugin to extract email attachments
    fnx


Leave a Reply