1import win32com.client #pip install pypiwin32 to work with windows operating sysytm
2import datetime
3import os
4
5# To get today's date in 'day-month-year' format(01-12-2017).
6dateToday=datetime.datetime.today()
7FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year))
8
9# Creating an object for the outlook application.
10outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
11# Creating an object to access Inbox of the outlook.
12inbox=outlook.GetDefaultFolder(6)
13# Creating an object to access items inside the inbox of outlook.
14messages=inbox.Items
15
16def save_attachments(subject,which_item,file_name):
17 # To iterate through inbox emails using inbox.Items object.
18 for message in messages:
19 if (message.Subject == subject):
20 body_content = message.body
21 # Creating an object for the message.Attachments.
22 attachment = message.Attachments
23 # To check which item is selected among the attacments.
24 print (message.Attachments.Item(which_item))
25 # To iterate through email items using message.Attachments object.
26 for attachment in message.Attachments:
27 # To save the perticular attachment at the desired location in your hard disk.
28 attachment.SaveAsFile(os.path.join("D:\Script\Monitoring",file_name))
29 break
30