[英]How to save MS Outlook attachments from specific sender and date using Python
I am a bit new to coding and I am trying to understand how to get Python to save MS Outlook attachments from a specific sender.我对编码有点陌生,我试图了解如何让 Python 保存来自特定发件人的 MS Outlook 附件。 I currently receive the same email from the same person each day regarding data that I need to save to a specific folder.我目前每天都会收到来自同一个人的关于我需要保存到特定文件夹的数据的相同电子邮件。 Below are the requirements I am trying to meet:以下是我试图满足的要求:
I have seen some posts on using win32com.client but have not had much luck getting it to work with MS Outlook.我看过一些关于使用 win32com.client 的帖子,但没有太多运气让它与 MS Outlook 一起工作。 I will attach some code I have tried below.我将附上我在下面尝试过的一些代码。 I appreciate any feedback!我感谢任何反馈!
import win32com.client
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
attachments = message.attachments
for attachment in attachments:
pass
You almost got it, add filter to the sender email address你差不多明白了,为发件人电子邮件地址添加过滤器
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)
Filter = "[SenderEmailAddress] = '0m3r@email.com'"
Items = Inbox.Items.Restrict(Filter)
Item = Items.GetFirst()
for attachment in Item.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(r"C:\path\to\my\folder\Attachment.xlsx")
Python 3.8 on windows Windows 上的 Python 3.8
def saveAttachments(email:object):
for attachedFile in email.Attachments: #iterate over the attachments
try:
filename = attachedFile.FileName
attachedFile.SaveAsFile("C:\\EmailAttachmentDump\\"+filename) #Filepath must exist already
except Exception as e:
print(e)
for mailItem in inbox.Items:
#Here you just need to bould your own conditions
if mailItem.Sender == "x" or mailItem.SenderName == "y":
saveAttachments(mailItem)
The actual conditions you can change to your liking.您可以根据自己的喜好更改实际情况。 I would recommend referring to the Object model for Outlook MailItem objects: https://docs.microsoft.com/en-gb/office/vba/api/outlook.mailitem Specifically its Properties我建议参考 Outlook MailItem 对象的对象模型: https : //docs.microsoft.com/en-gb/office/vba/api/outlook.mailitem特别是它的属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.