How to Auto Save Specific Email Attachments with Outlook VBA?
“Is there any way to auto-save specific email attachments in Outlook?” This is the most asked query by many of the Outlook users. Because there are lots of users who want to save only some specific file format attachments from Outlook. But due to the unavailability of any direct methods they are not able to do this. Hence, In this article, we are going to discuss how outlook vba save attachment. But before starting the blog let’s discuss what is VBA and what uses it?
What is VBA?
Basically, VBA stands for Visual Basic for Application, it helps the users to control Microsoft Outlook within Microsoft Outlook. With the help of VBA codes, users can create macros that can help to perform a complicated and repetitive task in Outlook which is not possible in Outlook. One of the most common use cases of VBA in Outlook is to automate email-related tasks, such as auto save specific email attachments with Outlook VBA.
VBA allows users to take all advantage of the Outlook object model with application-level events. This feature can be particularly useful for individuals that frequently receive emails with certain types of attachments that need to be saved or processed separately.
How to Auto Save Specific Email Attachments with Outlook VBA?
After understanding the VBA in Outlook let’s move towards the method to save attachments in Outlook.
Note: This article contains a programming task so make sure to do the task carefully at your own risk.
Before starting to write a VBScript first you have to create a folder in any local drive on your computer. And always make sure that the folder has enough space to save all the attachments from Outlook. If there is not that much space available, then macros not going to save all attachments.
Now let’s see the steps to auto-save email attachments with Outlook VBA
1. Press Alt+F11 to open the VB editor
2. Once the editor is open copy and paste the below VBScript
Public WithEvents olItems As Outlook.Items
Private Sub Application_Startup()
Set olItems = Session.GetDefaultFolder(olFolderInbox).Items
End SubPrivate Sub olItems_ItemAdd(ByVal Item As Object)
Dim NewMail As Outlook.MailItem
Dim Atts As Attachments
Dim Att As Attachment
Dim strPath As String
Dim strName As StringIf Item.Class = olMail Then
Set NewMail = Item
End IfSet Atts = Item.Attachments
If Atts.Count > 0 Then
For Each Att In Atts
‘Replace “test” with what you want to look for in attachment name
If InStr(LCase(Att.FileName), “test”) > 0 Then
‘Use your wanted destination folder path to save the attachments
strPath = “C:\Attachments\”
strName = NewMail.Subject & ” ” & Chr(45) & ” ” & Att.FileName
Att.SaveAsFile strPath & strName
End If
Next
End If
End Sub
3. Now, go back to MS Outlook and select the emails from which the specific attachments need to save
4. Then, enable all macros and hit Alt+F8 keys to start the saving
5. Now, choose ExecuteSavin and then Run
6. After that Browse For Folder option to save attachments from Outlook emails
7. Now, choose the location to save Outlook attachments
Limitations for Using Manual Method
Here are the limitations provided for this manual approach to auto save specific email attachments with outlook VBA:
- The script lacks error handling mechanisms. If any error occurs, the script will fail automatically without notifying the user.
- It requires manual editing for the script for any changes you want to make. Which reduces Flexibility and maintainability.
- The script doesn’t account for special characters in your attachment files which can issue while saving your file.
- There is a lack of performance issue with a huge volume of emails and attachments to process.
Auto Save Specific Email Attachments with Outlook VBA Using Python
- Ensure python is installed on your system.
- Install the ‘pywin32’ library using pip which provides access to COM objects and connects with outlook.
- Run pip install pywin32 using python.
- This python script will connect to outlook and auto save your email attachments to outlook VBA with a specific keyword to your desired folder.
Steps to Save Email Attachments Using Python
Step 1. Open Outlook and Configure Security Settings.
Ensure that Outlook is configured to allow programmatic access. You may need to adjust security settings to allow access by Python scripts.
Step 2.Write the Python Script
Create a Python script, for example save_attachments.py, with the following code:
import os
import win32com.client
from datetime import datetime
def save_attachments():
# Connect to Outlook
outlook = win32com.client.Dispatch(“Outlook.Application”).GetNamespace(“MAPI”)
inbox = outlook.GetDefaultFolder(6) # 6 refers to the inbox folder
messages = inbox.Items
# Set your destination path
save_path = “C:\\Attachments\\”
if not os.path.exists(save_path):
os.makedirs(save_path)
# Loop through the messages in the inbox
for message in messages:
try:
if message.Class == 43: # 43 is the class for MailItem
attachments = message.Attachments
if attachments.Count > 0:
for attachment in attachments:
# Check for specific keyword in attachment name
if “test” in attachment.FileName.lower():
# Create a safe file name
subject = message.Subject
date_str = datetime.now().strftime(“%Y%m%d%H%M%S”)
safe_subject = “”.join([c if c.isalnum() else “_” for c in subject])
filename = f”{safe_subject}_{date_str}_{attachment.FileName}”
filepath = os.path.join(save_path, filename)
# Save the attachment
attachment.SaveAsFile(filepath)
print(f”Saved attachment: {filepath}”)
except Exception as e:
print(f”Error processing message: {e}”)
if __name__ == “__main__”:
save_attachments()
Step 3: Customize your Script
- Adjust the keyword “test” in if “test” in attachment.FileName.lower(): to filter attachments by the desired keyword.
- Change save_path to your desired directory where attachments should be saved.
Step 4: Run the Script
- Save the script and run it using Python.
Run python save_attachments.py
Also Read: How to Extract Outlook Attachments to a Folder
Tech Insider Tip
There are many users who want to save specific attachments from Outlook. We have provided you with two manual methods to accomplish the task efficiently. If you want to go other way you can use EmailDoctor Outlook Attachment Extractor that can easily save email attachments in outlook.
FAQ (Frequently Asked Questions)
Q) Where does Outlook save VBA code?
They are stored in a file that is named as VBA Project OTM. This file is a product storage file and isn’t meant for distribution purpose. Outlook doesn’t provide a direct means to manage OTM files.
Q) How do I save a specific email in Outlook?
In Mail, from the message list, select the message you want to save so it opens in the reading pane, or double-click the message to open it in a new window. From the message header, select More actions > Save as.
Q) Is it possible to log or keep track of the auto save specific email attachments with Outlook VBA?
Absolutely. You can include additional code in the VBA macro to log information about the auto-saved attachments, such as file names, email subjects, senders. This log can be written to a text file, a database, or even a custom Outlook folder for future reference.