-1
我一直在嘗試將附件從.msg文件保存到PdF文件中,但名稱不同。任何人都可以請幫助我如何進一步進行?這是我的代碼。錯誤出現在代碼的最後一行。在python中保存帶有不同名稱的outlook附件
import win32com.client
import glob
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
path = "C:\\python\\test-email"
allFiles = glob.glob(path + "/*.msg")
working_path = os.getcwd()
for file in allFiles:
msg = outlook.OpenSharedItem(file)
count_attachments = msg.Attachments.Count
refno_start = text.find('Student ID') + 8
newname = "%s.pdf" % text[refno_start + 2:refno_start + 11]
if count_attachments > 0:
for item in range(count_attachments):
attached = msg.Attachments.Item(item + 1)
attached.SaveAsFile(working_path +'\\'+newname)
以下是錯誤messgae:
File "email-reader1.py", line 46, in <module>
attached.SaveAsFile(working_path +'\\'+newname)
File "<COMObject Item>", line 2, in SaveAsFile
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Out look', 'Cannot save the attachment. File name or directory name is not valid.',None, 0, -2147024773), None)
你有什麼錯誤? – bernie
你應該爲你的路徑生成使用'os.path.join',例如:'attached.SaveAsFile(os.path.join(working_path,newname))' – bernie
@bernie我已經試過這個並且得到了這個錯誤信息 – user2293224