使用Python在Outlook 2010中创建文件夹

3 投票
2 回答
2395 浏览
提问于 2025-04-17 23:36

我知道怎么用下面的代码获取Outlook 2010中文件夹的名字:

import win32com.client

ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)

那么我该怎么在Folder(2)里添加一个文件夹呢?我试过使用Folders.Add 方法,就像在这个链接里提到的,但没有成功。

2 个回答

0

在顶层添加文件夹和其他设置

来自@lowitty的明确答案(被大家投票为最佳答案)效果很好。

我参考了lowitty的答案,创建了一个子文件夹和一个顶层文件夹。

我还使用了我自己开发时用到的一些设置,希望这些也能帮助到其他人。

可以调用Python解释器,或者修改下面的内容并作为脚本运行:

>>> import win32com.client as win32
>>> import pythoncom
>>> app = win32.gencache.EnsureDispatch("Outlook.Application", pythoncom.CoInitialize())
>>> namespace = app.GetNamespace("MAPI")
>>> sent_folder = namespace.Folders["email@address.com"].Folders["Sent Items"]
>>> sent_folder.Name

'Sent Items'

>>> sent_folder.Folders.Add("Test")

<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x2320338244592> 
# And created "Test" as a subfolder under the "Sent Items" folder.

>>> namespace.Folders["email@address.com"].Folders.Add("Hello")

<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x2320338445712>
# And created a "Hello" folder at the top level.
5

我觉得你可能犯了个小错误,Add 这个函数是属于 Folders 的。它并不是指某一个特定的文件夹,比如 Folders(2)

你可以试试下面的代码,应该能正常运行:

import win32com.client

ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)
inbox.Folders.Add("My Folder Src")

撰写回答