如何从电子邮件下载附件并保留原始文件名?使用Python / outlook

时间:2013-08-14 02:05:46

标签: python outlook save attachment pywin32

我正在尝试使用Python和Windows扩展程序从outlook下载电子邮件中的附件,到目前为止我已尝试过以下内容:

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")

此代码将文件保存在文件名下:“File_name”。有什么办法可以使用原始文件名作为我用来保存的文件名吗?

2 个答案:

答案 0 :(得分:3)

当然,请使用Attachment.FileName属性(将其与要保存附件的目录名连接)。

答案 1 :(得分:1)

不要使用文件名,只需提供要保存文件的位置:

import os

attachment.SaveASFile(os.path.join('c:', 'your_dir_name'))