Automatically Download Email Attachment with Python | by KahEm Chu | Towards Data Science

Have you been in a position where you search over your mailbox to download all the attachments needed? Then maybe you leave and come back forgot where you have stopped? Perhaps you still have to save them to different directories or folder afterwards?
I have been in that position before. That is why I want to automate the process of downloading the attachment to the correct directory. After that, perform a transformation to the email’s attachment accordingly.
In this article, I would compare the possible Python libraries for the solution and share how I automate the process with Python.
smtplib is not one of the choices in my case, as its only capable of sending emails, while imaplib require a username and password which is not favorable. Hence, I chose pywin32.
There is no official documentation for pywin32 available. For now, we can only refer to the reference of the Outlook MailItem in Visual Basic for Application (VBA) to learn about the available functions to manipulate the mailbox and the mails. Then, the example cannot be used directly when you are scripting in Python. There is also some good application example of pywin32 on various technical writing websites, but they are not complete.
This article covers all the basic stuff you need to know to use pywin32 for accessing your Outlook Mailbox.
Import Modules
Import Modules
The very first step.
# pip install pywin32  #if you not installed yetimport win32com.client
2. Establish a Connection to Outlook
# set up connection to outlookoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
3. Some Basic Methods / Properties on MailItem Manipulation
(1) Accessing to the Inbox.
inbox = outlook.GetDefaultFolder(6)# for sub folder, add <.folder("your folder name")>inbox = outlook.GetDefaultFolder(6).folders("Testing")
6 is the index of the inbox. The index of other common items is as below.
3 Deleted Items4 Outbox 5 Sent Items6 Inbox16 Drafts
You may check the index of other folders by using the source code below. (Reference C2)
import win32com.clientoutlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")for i in range(50):  try:    box = outlook.GetDefaultFolder(i)    name = box.Name    print(i, name)  except:    pass
(2) Read the Email
# Access to the email in the inboxmessages = inbox.Items# get the first emailmessage = messages.GetFirst()# get the last email#message = messages.GetLast()# to loop thru the email in the inbox while True:  try:    print(message.subject) # get the subject of the email    # if you use messages.GetFirst() earlier    message = messages.GetNext()     # if you use messages.GetPrevious() earlier     #message = messages.GetPrevious()  except:    # if you use messages.GetFirst() earlier    message = messages.GetNext()     # if you use messages.GetPrevious() earlier     #message = messages.GetPrevious()
The above example shows how to print the subject of all of the email in the Inbox. Other than the subject, there are other properties we can print or use as criteria to define a conditional statement. The below shown some of the common properties.
message.subjectmessage.senton               # return the date & time email sentmessage.senton.date()message.senton.time()message.sendermessage.SenderEmailAddressmessage.Attachments          # return all attachments in the email
Note that the messages.GetFirst() or messages.GetNext() which end with a pair of parenthesis is referring to a method we can use to manipulate the mailbox, while the message.subject or message.senton is referring to the properties of the email, and it is not case sensitive when you using Python. Hence, you may refer to the documentation of MailItem in VB which can be found in Reference C1 at the bottom, for the complete MailItem properties list. (I haven’t tried all of it, but most of it can be applies.)
(3) Download an Email Attachment.
attachments = message.Attachments# return the first item in attachmentsattachment = attachments.Item(1)# the name of attachment file      attachment_name = str(attachment).lower()attachment.SaveASFile(path+ '\\' + attachment_name)
4. Complete Example
# import librariesimport win32com.clientimport re# set up connection to outlookoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")inbox = outlook.GetDefaultFolder(6)messages = inbox.Itemsmessage = messages.GetFirst()today_date = str(datetime.date.today())while True:  try:    current_sender = str(message.Sender).lower()    current_subject = str(message.Subject).lower()    # find the email from a specific sender with a specific subject    # condition    if re.search('Subject Title',current_subject) != None and    re.search(sender_name,current_sender) != None:      print(current_subject) # verify the subject      print(current_sender)  # verify the sender      attachments = message.Attachments      attachment = attachments.Item(1)      attachment_name = str(attachment).lower()      attachment.SaveASFile(path + '\\' + attachment_name)    else:      pass    message = messages.GetNext()  except:    message = messages.GetNext()exit
The above is the complete example to download an email from a specific sender with a specific title to a specific path. You may change the condition according to your situation, for example, you may use message.senton.date() to obtain the email received on the date defined. Also, you may use nested if-else statement to save attachments in different directories, which is pretty handy when you are going to download a lot of attachments.
Subscribe on YouTube
Documentation for smtplib
Documentation for imaplib
MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events)Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook)
MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events)
Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook)
If you are interested in how to use pywin32 to automate Microsoft Excel Report, you may refer to this article, “Automate Excel with Python”.
If you are interested to create a chart or PivotChart with Python and share it as an email attachment automatically, Automate Excel Chart with Python.
Congrats and thanks for reading to the end. Hope you enjoy this article. ☺️