使用 python win32com 的 Outlook 仅读取电子邮件直到特定日期,之后不读取任何内容

问题描述 投票:0回答:1

下面是我使用 win32com 读取特定文件夹中的电子邮件的 Python 代码。


from logging import root
import os
import win32com.client
from datetime import datetime, timedelta
import zipfile

date_format = "%m/%d/%Y %H:%M"

def recursively_find_folder(folder, target_name):
    if folder.Name == target_name:
        return folder
    for subfolder in folder.Folders:
        found_folder = recursively_find_folder(subfolder, target_name)
        if found_folder:
            return found_folder

#function to check the emails mentioned in outlook folder and down load the attachements based on email subject
def download_attachments(folder_name, output_folder, start_time, end_time, target_subject):
    outlook_app = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    #root_folder = outlook_app.Folders.Item(3)  # Assume the first folder is the mailbox
    root_folder = outlook_app.GetDefaultFolder(6)  # Assume the first folder is the mailbox
      
    target_folder = recursively_find_folder(root_folder, folder_name)

    if target_folder:
        print(f"Found folder: {target_folder.Name}")

        # Iterate through items in the folder
        items = target_folder.Items
        items.sort("[ReceivedTime]", True)

        for item in items:
            print("Item:: ", item)
            print("    Subject:: ", item.Subject.lower())
            print("    Recevied Time: ", item.ReceivedTime)
            # Check if the email matches the criteria
            for subject in target_subject:
                print(subject)
                print("Email Received Time: ", datetime.strptime(item.ReceivedTime.strftime('%m/%d/%Y %H:%M'), date_format))
                if (
                    start_time <= datetime.strptime(item.ReceivedTime.strftime('%m/%d/%Y %H:%M'), date_format) <= end_time
                    and subject.lower().strip() in item.Subject.lower().strip()
                    and item.Attachments.Count > 0
                ):
                    print(f"Processing email: {item.Subject}")
                    for attachment in item.Attachments:
                        # Save attachments to the output folder
                        attachment.SaveAsFile(os.path.join(output_folder, attachment.FileName))
                        print(f"Downloaded attachment: {attachment.FileName}")
                else:
                    print("Nothing Happened!!!")

    else:
        print(f"Folder '{folder_name}' not found.")
        
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

#function to find zip folder and unzip it
def find_and_unzip_report_file(folder_path, extraction_path):
    # Check if the folder exists
    if not os.path.exists(folder_path):
        print(f"Error: Folder '{folder_path}' not found.")
        return

    # Get a list of all files in the folder
    files = os.listdir(folder_path)

    # Find the report file based on the name pattern
    report_file = next((file for file in files if file.lower().startswith('report') and file.lower().endswith('.zip')), None)

    if report_file:
        # Construct the full path to the zip file
        zip_file_path = os.path.join(folder_path, report_file)

        # Create the extraction path if it doesn't exist
        os.makedirs(extraction_path, exist_ok=True)

        # Unzip the contents of the zip file
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.extractall(extraction_path)
        
        os.rename(folder_path + 'CC CM Provisioning - INC SLA - ALL.csv', folder_path + 'CC CM Provisioning - INC SLA - ALL' + '-' + report_file[7:24] + '.csv')
        
        os.remove(zip_file_path)
        print(f"Successfully unzipped '{zip_file_path}' to '{extraction_path}'.")
    else:
        print("Error: Report file not found in the specified folder.")


if __name__ == "__main__":
    folder_to_download = "service_tickets"
    output_directory = "//prod_drive/meta/downloads/"
    # Get the first day of the current month
   
    start_date_time = (datetime.today().replace(day=1, hour=23, minute=0, second=0, microsecond=0) - timedelta(days=1)).strftime('%m/%d/%Y %H:%M')
    
    end_date_time = (datetime.today().replace(day=1, hour=23, minute=10, second=0, microsecond=0) - timedelta(days=1)).strftime('%m/%d/%Y %H:%M') 
    date_format = "%m/%d/%Y %H:%M"
    start_time = datetime.strptime(start_date_time, date_format)
    print("Start Time:", start_time)
    end_time = datetime.strptime(end_date_time, date_format)
    print("End Time: ", end_time)
    target_subject = ['CC CM Provisioning - INC SLA - ALL','CC CM Provisioning - SCTASK SLA - All','CC CM Provisioning - SCTASK - All']


    download_attachments(folder_to_download, output_directory, start_time, end_time, target_subject)
    
    find_and_unzip_report_file(output_directory, output_directory)

但是上面的代码只能读取 2024 年 5 月 31 日之前的电子邮件,之后则不会读取任何内容。我也尝试运行其他文件夹的代码,但结果是一样的。电子邮件仅在 05/31 之前扫描/处理。

有人可以告诉我我的代码中到底有什么问题吗?找不到任何与此相关的类似帖子。

python python-3.x outlook win32com
1个回答
0
投票

您的代码假设文件夹中只能有

MailItem
对象。如果您有 NDR(由
ReportItem
对象表示),则
ReceivedTime
优先权不会公开,您的代码将会出错。

© www.soinside.com 2019 - 2024. All rights reserved.