繁体   English   中英

使用 python 保存 outlook 附件

[英]save outlook attachments with python

每个星期一我都会收到主题标题略有改变的附件。 主题标题的固定部分是PB 报告,日期为星期一。 例如,我本周一收到了 email 的主题PB Report - 13.12.2021 ,上周的PB Report - 06.12.2021等等。 我想在此代码中实现GetLast以便仅获取最新发送的报告。 另外,我如何告诉 python 搜索以 PB Report 开头的主题,不要看标题的 rest。 我尝试将通配符(*)作为save_attachments('PB Report*') ,但没有奏效。

import datetime
import os
import win32com.client

path = r"C:/Users/greencolor/Desktop/Autoreport/"
today = datetime.date.today()

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items


def save_attachments(subject):
    for message in messages:
        if message.Subject == subject:
            for attachment in message.Attachments:
                print(attachment.FileName)
                attachment.SaveAsFile(os.path.join(path, str(attachment)))


if __name__ == "__main__":
    save_attachments('PB Report - 13.12.2021')

我也有替代代码,但是当我运行此代码时,我永远不会得到结果或错误。 它需要。

import os
import win32com.client
    
path = r"C:/Users/greencolor/Desktop/Autoreport/"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()


while message:
    if 'PB' in message.subject and 'Report' in message.subject:
        for attachment in message.Attachments:
            print(attachment.FileName)
            attachment.SaveAsFile(os.path.join(path, str(attachment)))

参数subject的通配符不起作用,因为在比较message.Subject == subject中的相等性时,参数subject被用作字符串。

您可以改为在消息主题上使用 string-method startswith ,例如message.Subject.startswith(subject_prefix)并使用通用前缀(例如save_attachments('PB Report - ') )调用您的方法。

此外,使用attachment.FileName构造输出文件路径。

您可以使用带有适当消息属性的GetLast()Sort()来过滤最新发送的报告 或者您可以解析消息主题中的日期并相应地对它们进行排序。 然而,这将值得另一个问题,自己的研究和进一步的规范和关注。

解决方案

一个示例解决方案可能如下(请参阅调整评论):

def save_attachments(subject_prefix): # changed parameter name
    messages.Sort("[ReceivedTime]", True)  # sort by received date: newest to oldest 
    for message in messages:
        if message.Subject.startswith(subject_prefix): # changed test
            print("saving attachments for:", message.Subject)
            for attachment in message.Attachments:
                print(attachment.FileName)
                attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))  # changed to file-name
            return  # exit after first matched message

如果您知道消息仅包含所需的消息,或者按日期排序,则可以使用GetLast()

message = messages.GetLast()
while message:  # to test if there is a (last) message at all
    # save attachment

相关问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM