【问题标题】:Pywin32 Outlook Restrict function stopped workingPywin32 Outlook 限制功能停止工作
【发布时间】:2020-08-15 21:46:41
【问题描述】:

我一直在使用下面的代码 sn-p 来获取过去 3 小时内收到的某个子文件夹中的每封电子邮件,并在处理之前从中提取一些业务信息,并且它已经运行了一周左右。但是,昨天由于某种原因,我注意到它没有正常工作,当我添加一个打印语句以查看哪些电子邮件发送到流程功能时,我注意到它从 3 月到现在发送了所有内容(超过 1000 封电子邮件) .

        outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
        api_folder = outlook.Folders.Item(1).Folders['Some Folder']

        start = datetime.datetime.now() - datetime.timedelta(hours=3)

        # 05/01/2020 05:23 AM is this the right format?

        start = start.strftime('%m/%d/%Y %H:%M %p')

        messages = api_folder.Items.Restrict("[ReceivedTime] >= '" + start + "'")

        # This prints emails that shouldnt be here after Restrict()
        for msg in messages:
            print(f"{msg.Subject} - {msg.ReceivedTime}")

我很确定这可能是调用 Restrict 的方式或时间格式上的一个非常愚蠢的错误,但是由于我是编程新手,所以我无法找到导致功能异常。

非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: python email outlook pywin32 win32com


    【解决方案1】:

    python 中的以下代码对我来说工作正常,请不要包含 'seconds' 限制,仅限制为日期(mm/dd/yyyy)、小时和分钟 + 提及 AM/PM 用于邮件(例如:12/22/2021 09:44 AM),并应提供字符串(转换后)格式的日期时间对象以应用限制。

    def read_mails(subject_line: str, start_datetime: datetime, end_datetime: datetime):
        """
        Read the outlook inbox and saves the attachments in the selected destination directory
    
        """
        print("\nReading messages..")
    
        # get outlook app
        outlook = win32com.client.Dispatch("outlook.application")
    
        # getting path for saving attachments
        destination_path = ask_input("select folder to save")
    
        print("Checking Inbox...")
        inbox = outlook.GetNamespace("MAPI").GetDefaultFolder(6)
    
        restriction = (
            "[ReceivedTime] >= '"
            + start_datetime.strftime("%m/%d/%Y %H:%M %p")
            + "' And [ReceivedTime] <= '"
            + end_datetime.strftime("%m/%d/%Y %H:%M %p")
            + "'"
        )
    
        # reading restricted inbox messages
        retriving_messages = inbox.Items.Restrict(restriction)
        print("Restriction: ", restriction)
    
        for message in list(retriving_messages):
            if subject_line.lower() in message.subject.lower():
                save_attachments(destination_path, message)
            else:
                continue
    

    【讨论】:

      【解决方案2】:

      虽然日期和时间通常以Date 格式存储,但FindRestrict 方法要求将日期和时间转换为字符串表示形式。要确保日期的格式符合 Microsoft Outlook 的预期,请使用 strftime(或 VBA 中的 Format)函数。并确保 Outlook 理解它:

      api_folder.Items.Restrict("urn:schemas:httpmail:datereceived" >= '9/15/2019 12:00 AM')
      

      注意,您可以在 Outlook 中手动配置所需的过滤器以获取字符串表示形式并在代码中使用它。

      【讨论】:

        猜你喜欢
        • 2017-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多