Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import win32com.client # You need to install the module: "pypiwin32"
- Outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Opens Microsoft Outlook
- def getFolderIndex(COMObjectFolders, folderName):
- i = 1 # Folder index. Used to access the right main folder.
- while True:
- try:
- if COMObjectFolders.Item(i).Name == folderName:
- break # At this point we have the right index
- else:
- i += 1 # Next Folder
- except:
- i = None # We did not find out our folder index
- break
- return i
- def getFolder(COMObjectFolders, folderName): # Wrapper
- return COMObjectFolders.Item(getFolderIndex(COMObjectFolders, folderName))
- myMainFolder = getFolder(Outlook.Folders, "[[your email (imap) or main folder name]]")
- mySubFolder = getFolder(myMainFolder.Folders, "[[Subfolder such as Inbox or whatever]]")
- myEmails = mySubFolder.Items
- def extractAttachments(COMObjectMailItems, howMany = "all"):
- # howMany parameter controls how many last received emails to go through
- if howMany == "all":
- numberEmails = COMObjectMailItems.Count # Used to loop by the number of emails in the folder
- lastEmail = 0 # The index-1 of the email to stop at. Used in range().
- else:
- numberEmails = COMObjectMailItems.Count
- lastEmail = numberEmails - howMany
- outputAttachments = dict() # Used for output. Which is a dict {'filename-date' : attachment}
- for i in range(numberEmails, lastEmail, -1):
- message = COMObjectMailItems.Item(i)
- attachmentsList = message.Attachments
- if attachmentsList.Count > 0:
- n = attachmentsList.Count
- for j in range(1, n+1):
- outputAttachments[str(attachmentsList.Item(j)) + "_" + message.CreationTime.Format()] =\
- attachmentsList.Item(j)
- return(outputAttachments)
- savePath = 'C:\\Users\\[[user name here, or change path competely]]\\Desktop\\Inbox' # Where to save attachments
- myAttachments = extractAttachments(myEmails, howMany=1) # howMany = 1 was used to check the most recent email received
- def saveAttachments(attachments, path):
- for key, attachment in attachments.items():
- attachment.SaveAsFile(path + '\\' + str(attachment))
- saveAttachments(myAttachments, savePath) # Has an obvious side effect - Saves files to disk
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement