【发布时间】:2016-01-06 12:46:02
【问题描述】:
我有一个简单的程序,它使用 win32com.client 的 Dispatch 连接到 Outlook 邮箱,浏览电子邮件并在本地保存附件。
如果我想保存一个附件,我会为它处理一个路径和一个文件名,这样我就可以使用方法 attachment.SaveAsFile(file) 将它保存在本地。在某些情况下,路径 + 文件名超过了 255 个字符(加起来)的限制,因此会失败。
我想知道如何更改该方法的工作目录。如果我尝试将路径和文件名分开,请使用 os.chdir() 将我的工作目录更改为提取的路径并使用 SaveAsFile() 仅包含文件名,它将保存在临时文件夹中(意思是os.chdir() 不会影响该方法)
临时文件夹(如果有帮助): C:\Users[USERNAME]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook\GKSDWWYZ
那么,如何更改 SaveAsFile() 方法的默认工作目录?
这就是我正在做的:
def save_attachment_as_file(att, file):
"""
att - an email attachment
file - to full path and filename to save the attachment as
"""
# seperate the path and filename
file_path = file[:file.rfind("\\")]
file_name = file[file.rfind("\\")+1:]
# check that both seperate lengths does not exceed the limit
if not check_length(file_path) or not check_length(file_name):
return
# save the currect working directory
working_path = getcwd()
# change the working directory to the provided path
chdir(file_path)
# save the attachment
att.SaveAsFile(file_name)
# change back the working directory
chdir(working_path)
print("Created:", file)
【问题讨论】:
标签: outlook python-3.4 email-attachments win32com working-directory