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

Nuitka打包Python程序异机调用pywin32发邮件报路径不存在错误求助

问题:Nuitka打包的Python程序在其他电脑上无法发送带附件的Outlook邮件

问题描述

用Python结合Nuitka开发的应用,在开发电脑上运行正常,通过pywin32调用Outlook发送带附件的邮件功能正常。但分发到其他电脑运行时,出现如下异常:

发送邮件失败: (-2147352567, 发生异常, (4096, 'Microsoft Outlook', '路径不存在。请确认路径是否正确', None, 0, -2147024893), None)

相关代码

import win32com.client
import pythoncom
def Send_mail():
    try:
        pythoncom.CoInitialize() # Ensure COM initialization
#        destination = email_entry.get()
        ol = win32com.client.Dispatch('Outlook.Application')
        # size of the new email
        olmailitem = 0x0
        newmail = ol.CreateItem(olmailitem)
        newmail.Subject = 'Test'
        newmail.To = ';'.join(recipient_emails)
        #newmail.CC = 'xyz@gmail.com'
    
        newmail.Body= 'Hello'
    
        attach = 'file.xlsx' # File created with script, stored in executable folder
        newmail.Attachments.Add(attach)
    
        newmail.Display()
        # Clear recipient email list
        recipient_emails.clear()
        
    except Exception as e:
        # Show error message if any exception occurs
        messagebox.showerror("Error", f"Failed to send email: {str(e)}")
        
def add_email():
    email = email_entry.get().strip()
    if email:
        recipient_emails.append(email)
        email_entry.delete(0, tk.END)
    
    tree_mail.insert('', tk.END, values=email)

解决方案

1. 修正附件路径为绝对路径

问题核心是相对路径在打包后的程序中无法正确解析。开发环境中脚本的工作目录是代码所在目录,但Nuitka打包后的exe运行时,工作目录可能不是exe所在目录,导致相对路径找不到文件。

修改代码,获取exe所在的绝对目录后拼接附件路径:

import os
import sys

def Send_mail():
    try:
        pythoncom.CoInitialize()
        # 获取可执行文件所在的绝对目录
        exe_dir = os.path.dirname(os.path.abspath(sys.executable))
        # 拼接附件的绝对路径
        attach_path = os.path.join(exe_dir, 'file.xlsx')
        
        ol = win32com.client.Dispatch('Outlook.Application')
        olmailitem = 0x0
        newmail = ol.CreateItem(olmailitem)
        newmail.Subject = 'Test'
        newmail.To = ';'.join(recipient_emails)
        newmail.Body= 'Hello'
        
        # 使用绝对路径添加附件
        newmail.Attachments.Add(attach_path)
        
        newmail.Display()
        recipient_emails.clear()
        
    except Exception as e:
        messagebox.showerror("Error", f"Failed to send email: {str(e)}")

2. 确保附件文件被正确打包

打包时需要明确告诉Nuitka要包含附件文件,否则exe目录下不会有file.xlsx。使用以下打包命令:

python -m nuitka --standalone --include-data-files=file.xlsx=. your_script.py
  • --include-data-files=file.xlsx=. 表示将当前目录下的file.xlsx复制到打包后的exe所在目录。

3. 额外检查(可选)

  • 目标电脑需安装Microsoft Outlook,且已配置好可用的邮件账户;
  • 确保目标电脑上的Outlook有足够权限访问附件文件(避免文件被占用或权限不足)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:50:16