Search code examples
pythonoutlooksaveattachmentpywin32

how to download attachments from e-mail and keep original filename? using Python/outlook


I'm trying to download the attachments in an email from outlook using Python and the windows extensions, so far I've tried the following:

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('Subfolder')
messages = inbox.Items
message = messages.GetLast() #open last message
attachments = message.Attachments #assign attachments to attachment variable
attachment = attachments.Item(1)
attachment.SaveASFile("File_name")

This code will save the file under the filename: "File_name" . Is there any way I could use the original file name as the file name I'm using to save?


Solution

  • Sure, use the Attachment.FileName property (concatenate it with the directory name where you want to save the attachment).