对Python来说是个新手。我的目标是仅将.xls和.docx文件类型的某些发件人的电子邮件附件下载到指定文件夹。我的发件人条件有效,但无法让程序筛选到我想要的特定文件类型。下面的代码从列出的发件人下载所有附件,包括图像签名(不需要)。下载的附件包含将在df中进一步使用的数据。我想把它保存在win32com中,因为我有其他使用它的工作电子邮件抓取程序。我感谢你的建议
部分工作代码:
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
Items = inbox.Items
Item = Items.GetFirst()
def saveAttachments(email:object):
for attachedFile in email.Attachments:
try:
filename = attachedFile.FileName
attachedFile.SaveAsFile("C:\\Outputfolder"+filename)
except Exception as e:
print(e)
for mailItem in inbox.Items:
if mailItem.SenderName == "John Smith" or mailItem.SenderName == "Mike Miller":
saveAttachments(mailItem)
当前,您将所有附加文件保存在磁盘上:
Attachment.FileName属性返回表示附件文件名的字符串。因此,通过提取文件扩展名来解析文件名将帮助您筛选应该保存在磁盘上的文件
此外,您可能对避免邮件正文中用于内联图像的隐藏附件感兴趣。下面是VBA中的示例代码(Outlook对象模型对于所有编程语言都是通用的,我不熟悉Python),它统计可见附件:
您还可以检查邮件正文(请参见Outlook项目的
HTMLBody
属性)是否包含PR_ATTACH_CONTENT_ID
属性值。如果不是,则如果未显式设置PR_ATTACHMENT_HIDDEN
属性,则用户可以看到附加的属性此外,您可能会发现Sending Outlook Email with embedded image using VBS线程很有用
首先,不要循环遍历文件夹中的所有项-使用
Items.Find/FindNext
或Items.Restrict
查询SenderName
属性-请参见https://docs.microsoft.com/en-us/office/vba/api/outlook.items.restrict至于附件,图像附件与任何其他附件没有任何区别。您可以检查文件扩展名或大小。您还可以使用
Attachment.PropertyAccessor.GetProperty
读取PR_ATTACH_CONTENT_ID
属性(DASL名称http://schemas.microsoft.com/mapi/proptag/0x3712001F
),并检查它是否在MailItem.HTMLBody
属性的img标记中使用相关问题 更多 >
编程相关推荐