Automatically download Outlook attachments with Python

How to Automatically Download Outlook Email Attachments with Python

**This will only work on Windows PC Devices and Microsoft Outlook email client**

Use pywin32 to save and file any Outlook email attachment

Jump to Full Code↓

Do you receive a weekly report via Outlook that you need to file manually each week? Or maybe have a short email retention policy (and a short term memory) that makes you constantly lose files? Sure, doing this manually isn’t hard but learning how to automate short tasks can save you tons of time over the course of your career.

This article will teach you how to use Python to automate downloading any Outlook attachments and save them in a designated custom file. You will need python installed on your Windows PC computer (this will NOT work on a Mac). We recommend running this in a Jupyter Notebook, so you can easily run each code block, section by section.


First, import the win32com.client and os packages.


import win32com.client
import os

#having issues installing win32com? try the below (without the hashtag)

#pip install pypiwin32
#pip install pywin32
#python -m pip install pypiwin32

Then, Copy & Paste the below save_outook_attachments Function into a Code Editor

The below Python function was written by our team to ensure you have everything you need to automate downloading Outlook attachments. Try running the below function to make sure it works without an errors. You can copy and paste the below into whatever editor you use.

def save_outlook_attachments(folder_name,subject_line,save_location):
    outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    outlook_mailbox =outlook_application.Folders.Item(1) 
#this is your default mailbox. if you have multiple mailboxes in outlook try increasing this number (2,3,4 etc.)
   
    #Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
    for folder in outlook_mailbox.Folders:
        if folder.Name == folder_name:
            found_folder = folder
            print('Folder Searched:' + found_folder.Name)
   
    #Sorts all emails in folder by date (descending)
    folder_emails = found_folder.Items
    folder_emails.Sort("[ReceivedTime]", True)
    
    #Looks for correct email by searching for an email containing subject_line 
    for email in folder_emails:
        if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "=="
            print('Found email with subject '+ email.Subject + ' sent on ' + email.SentOn.strftime('%m-%d-%y'))
            found_email = email
            break
    #Gets email attachment from email and saves to file location
    num_email_attachments = len([x for x in found_email.attachments])+1
    for attachment_num in range(1, num_email_attachments):
        attachment = found_email.attachments.Item(attachment_num)
        attachment_name = str(attachment)
        print('Attachment Number ' + str(attachment_num) +' - File Name : '+attachment_name)
        save_file_path = os.path.join (save_location,attachment_name)
        attachment.SaveAsFile(save_file_path)
        print('Attachment ' + str(attachment) +" saved to " + save_file_path)

Next, define your email criteria

In order to automate downloading Outlook attachments with Python, we need to provide the program information about what emails we are looking for. This includes

  1. folder_name = which folder the email lives in (Inbox? or a Custom Outlook Folder?)
  2. subject_line = a phrase that will help us identify the correct email via subject line (i.e find the last email that contains “Weekly Report”)
  3. save_location = this is the file path where you want the email attachment to automatically save to
folder_name = 'Inbox'
subject_line = 'Weekly Report' #case senstive, must contain phrase 
save_location = r'C:\Users\YOUR_USER_NAME_HERE\Documents\Weekly Reports' 
#the r before the file location is not a typo! It helps format the code correctly.

Finally, you’re ready to run!

Copy & paste the below code under your defined variables and hit Run! You should then be able to automatically download any Outlook attachment automatically with Python and save it to a designated file location. This code will produce output letting you know if you’re successful or not. However, you can always check your specified save location yourself, to make sure the attachments saved in the correct spot.

save_outlook_attachments(folder_name,subject_line,save_location)

Output:

>Folder Searched:Inbox
>Found email with subject Weekly Report sent on 11-12-22
>Attachment Number 1 - File Name : Weekly Report.csv
>Attachment Weekly Report.csv saved to C:\Users\YOUR_USERNAME_HERE\Documents\Weekly Report.csv

How to Automatically Download Outlook Attachments – Python Full Code

import win32com.client
import os

#Define Save Outlook Attachments Function
def save_outlook_attachments(folder_name,subject_line,save_location):
    outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    outlook_mailbox =outlook_application.Folders.Item(1) 
#this is your default mailbox. if you have multiple mailboxes in outlook try increasing this number (2,3,4 etc.)
   
    #Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
    for folder in outlook_mailbox.Folders:
        if folder.Name == folder_name:
            found_folder = folder
            print('Folder Searched:' + found_folder.Name)
   
    #Sorts all emails in folder by date (descending)
    folder_emails = found_folder.Items
    folder_emails.Sort("[ReceivedTime]", True)
    
    #Looks for correct email by searching for an email containing subject_line 
    for email in folder_emails:
        if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "=="
            print('Found email with subject '+ email.Subject + ' sent on ' + email.SentOn.strftime('%m-%d-%y'))
            found_email = email
            break
    #Gets email attachment from email and saves to file location
    num_email_attachments = len([x for x in found_email.attachments])+1
    for attachment_num in range(1, num_email_attachments):
        attachment = found_email.attachments.Item(attachment_num)
        attachment_name = str(attachment)
        print('Attachment Number ' + str(attachment_num) +' - File Name : '+attachment_name)
        save_file_path = os.path.join (save_location,attachment_name)
        attachment.SaveAsFile(save_file_path)
        print('Attachment ' + str(attachment) +" saved to " + save_file_path)

#Define Variables
folder_name = 'Inbox'
subject_line = 'Weekly Report' #case senstive, must contain phrase 
save_location = r'C:\Users\YOUR_USER_NAME_HERE\Documents\Weekly Reports'
#the r before the file location is not a typo! It helps format the code correctly.

#Run Function
save_outlook_attachments(folder_name,subject_line,save_location)

Comments

26 responses to “How to Automatically Download Outlook Email Attachments with Python”

  1. […] time over the course of your career. Need this code as a reusable method instead? Try our article How to Automatically Download Outlook Email Attachments with Python […]

  2. Thank you for your post. I really enjoyed reading it, especially because it addressed my issue. It helped me a lot and I hope it will also help others.

  3. You’ve been great to me. Thank you!

  4. I’m so in love with this. You did a great job!!

  5. Thanks for these pointers. One thing I additionally believe is always that credit cards supplying a 0 interest rate often attract consumers with zero interest, instant acceptance and easy internet balance transfers, nonetheless beware of the real factor that will certainly void that 0 easy neighborhood annual percentage rate plus throw you out into the poor house quick.

  6. I am usually to running a blog and i really appreciate your content. The article has really peaks my interest. I am going to bookmark your site and maintain checking for brand new information.

  7. I cling on to listening to the news bulletin talk about receiving free online grant applications so I have been looking around for the finest site to get one. Could you advise me please, where could i acquire some?

  8. Via my examination, shopping for technology online can for sure be expensive, but there are some principles that you can use to acquire the best bargains. There are constantly ways to discover discount specials that could make one to hold the best technology products at the smallest prices. Thanks for your blog post.

  9. Pretty component of content. I just stumbled upon your site and in accession capital to say that I acquire in fact enjoyed account your weblog posts. Any way I抣l be subscribing to your augment or even I fulfillment you get entry to constantly rapidly.

  10. One thing I’ve noticed is there are plenty of beliefs regarding the banking companies intentions when talking about foreclosure. One fable in particular is the fact the bank desires your house. The lender wants your money, not your home. They want the amount of money they lent you having interest. Preventing the bank will simply draw the foreclosed final result. Thanks for your write-up.

  11. I discovered your blog site on google and check just a few of your early posts. Proceed to keep up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Looking for ahead to reading more from you afterward!?

  12. Sweet blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers

  13. I抦 not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back later on. Many thanks

  14. Your place is valueble for me. Thanks!?

  15. One more thing. I think that there are several travel insurance websites of respectable companies that allow you enter your journey details and obtain you the quotations. You can also purchase this international travel insurance policy on the web by using the credit card. All you need to do is usually to enter your current travel details and you can see the plans side-by-side. Merely find the system that suits your finances and needs after which use your bank credit card to buy them. Travel insurance online is a good way to do investigation for a respected company pertaining to international travel insurance. Thanks for giving your ideas.

  16. Great article and right to the point. I am not sure if this is really the best place to ask but do you guys have any ideea where to get some professional writers? Thanks 🙂

  17. excellent post, very informative. I ponder why the opposite experts of this sector don’t understand this. You should continue your writing. I am sure, you’ve a huge readers’ base already!

  18. I believe that avoiding highly processed foods will be the first step so that you can lose weight. They might taste beneficial, but prepared foods possess very little vitamins and minerals, making you take more only to have enough electricity to get over the day. In case you are constantly having these foods, converting to grain and other complex carbohydrates will let you have more energy while feeding on less. Good blog post.

  19. Thanks for the article. My spouse and i have always observed that many people are eager to lose weight simply because they wish to show up slim in addition to looking attractive. On the other hand, they do not often realize that there are additional benefits to losing weight also. Doctors declare that fat people have problems with a variety of illnesses that can be instantly attributed to the excess weight. The great thing is that people who’re overweight as well as suffering from different diseases are able to reduce the severity of their own illnesses by simply losing weight. It is easy to see a steady but noticeable improvement in health when even a bit of a amount of weight loss is realized.

  20. Attractive element of content. I just stumbled upon your weblog and in accession capital to say that I get actually loved account your weblog posts. Anyway I will be subscribing for your augment and even I achievement you get right of entry to persistently fast.

  21. I have noticed that over the course of creating a relationship with real estate homeowners, you’ll be able to come to understand that, in each and every real estate deal, a fee is paid. In the long run, FSBO sellers really don’t “save” the percentage. Rather, they fight to win the commission by way of doing a agent’s work. In doing so, they spend their money along with time to carry out, as best they might, the duties of an broker. Those assignments include getting known the home by means of marketing, showing the home to prospective buyers, creating a sense of buyer emergency in order to induce an offer, preparing home inspections, controlling qualification inspections with the loan provider, supervising maintenance tasks, and facilitating the closing.

  22. Also I believe that mesothelioma is a scarce form of most cancers that is commonly found in individuals previously exposed to asbestos. Cancerous tissue form while in the mesothelium, which is a protecting lining which covers almost all of the body’s body organs. These cells ordinarily form while in the lining on the lungs, abdomen, or the sac which actually encircles the heart. Thanks for giving your ideas.

  23. Thank you for sharing your knowledge of email marketing competitive analysis.

  24. Welcome email templates greet new subscribers.

  25. This is quality work regarding the topic! I guess I’ll have to bookmark this page. See my website QH6 for content about Article Marketing and I hope it gets your seal of approval, too!

  26. Your blog has really piqued my interest on this topic. Feel free to drop by my website FQ4 about Cosmetics.

Leave a Reply

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