You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取本地Outlook msg文件接收时间触发无法打开文件报错的问询

问题解决方法

错误原因

  • 你调用的filedialog.askopenfile()会直接打开选中的文件并返回文件对象,导致文件被Python占用,Outlook无法再次读取
  • outlook.OpenSharedItem()要求传入的参数是文件的路径字符串,而你传入的是askopenfile返回的文件对象,类型不匹配
  • 额外的逻辑问题:你代码中获取到msg.ReceivedTime后,又用固定时间重写了dt变量,最终无法拿到实际的邮件接收时间

修复方案

将文件选择的方法替换为filedialog.askopenfilename(),该方法仅返回选中文件的路径字符串,不会占用文件。修正后的完整代码如下:

from tkinter import *
from tkinter import filedialog
from tkinter import ttk
import pandas as pd
import numpy as np
from pandas import DataFrame
import win32com.client
import datetime
from datetime import datetime
from time import strftime

def your_script(file_path):
    outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
    # 打开邮件
    msg = outlook.OpenSharedItem(file_path)
    
    # 获取邮件接收日期
    dt = msg.ReceivedTime
    # 格式化时间
    dt = dt.strftime('%d-%b-%Y')
    print(dt)
    # 用完关闭邮件对象释放资源
    del msg

# 引导用户选择文件,仅返回文件路径
file_path = filedialog.askopenfilename(initialdir="/", title="select the first file",
                                       filetypes=(("Last quarters email", "*.msg"), ("all files", "*.*")))

if file_path: # 确认用户选择了文件才执行后续逻辑
    your_script(file_path)

注意事项

  • 运行代码前请确保Outlook客户端处于正常启动状态
  • 待读取的msg文件不要提前手动打开,避免出现占用冲突

内容的提问来源于stack exchange,提问作者PythonBeginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:30:02